简体   繁体   English

如何从 Android 发出 http 请求?

[英]How to make a http request from Android?

I am trying to make a mobile app and I'm currently creating the api for communicating with the server.我正在尝试制作一个移动应用程序,我目前正在创建 api 用于与服务器通信。 My code works fine on a normal maven project but when I add it to my android studio project I get errors when I try to read from the connection input stream.我的代码在正常的 maven 项目上工作正常,但是当我将它添加到我的 android 工作室项目时,当我尝试从连接输入 stream 读取时出现错误。

package client;

import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class CCH {

    //static private String host = "http://localhost:8080";
    static private String host ="https://radiant-bayou-97811.herokuapp.com";

    //GET REQUESTS
    public static Integer login(String username, String password){
        String tempurl = host + "/api/user/login/" + username + "/" + password;
        JSONObject jsonObject = getRequest(tempurl);
        if(jsonObject.has("login"))
            if(jsonObject.get("login").equals("true"))
                return 1;
            else
                return 0;
        else
            return 0;
    }
    public static JSONObject getPacient(String username){
        String tempurl = host + "/api/user/getPacient/" + username;
        return getRequest(tempurl);
    }
    public static JSONObject getIstoric(String username){
        String tempurl = host + "/api/user/pacient/istoric/" + username;
        return getRequest(tempurl);
    }
    public static JSONObject getDiagnostic(String username){
        String tempurl = host + "/api/user/pacient/diagnostic/" + username;
        return getRequest(tempurl);
    }
    //POST REQUESTS
    public static void sendData(String username,String time,String puls,String calorii,String nr_pasi,String nivel_oxigen,String calitate_somn){
        String tempurl = host+ "/api/user/pacient/importData";
        JSONObject jsonObject = new JSONObject();
        jsonObject.append("username",username);
        jsonObject.append("time",time);
        jsonObject.append("puls",puls);
        jsonObject.append("calorii",calorii);
        jsonObject.append("nr_pasi",nr_pasi);
        jsonObject.append("nivel_oxigen",nivel_oxigen);
        jsonObject.append("calitate_somn",calitate_somn);

        postRequest(tempurl,jsonObject);
    }
    public static JSONObject getRequest(String URL){
        JSONObject response = null;
        HttpURLConnection connection = null;
        try {



            URL url = new URL(URL);

            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");

            response = new JSONObject(readFromConnection(connection));




        }catch (Exception e){
            response = new JSONObject();
            response.append("Error!","Error on the client side contact the admin!");
            response.append("Error!!",e.getCause());
            e.printStackTrace();
        }
        finally {
            connection.disconnect();
            return response;
        }
    }
    public static void postRequest(String URL,JSONObject jsonObject){
        HttpURLConnection connection = null;
        try{
            URL url = new URL(URL);

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setRequestProperty("Accept", "application/json");

            connection.setDoOutput(true);

            OutputStream os = connection.getOutputStream();
            os.write(createJson(jsonObject).getBytes());
            System.out.println(createJson(jsonObject));
            os.flush();
            os.close();
            int responseCode = connection.getResponseCode();
        } catch (Exception e){
            System.out.println("Unable to make post request!");
            System.out.println(e.getCause());
            System.out.println(e.getStackTrace());
            System.out.println(URL);
        }
    }
    public static String readFromConnection(HttpURLConnection connection) throws IOException {
        StringBuilder content;
        BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        content = new StringBuilder();
        while ((line = input.readLine()) != null) {
            content.append(line);
        }
        return content.toString();
    }
    public static String createJson(JSONObject jsonObject){
            StringBuilder tempString = new StringBuilder();
            tempString.append("{");
            int count = 0;
            for(String key : jsonObject.keySet()){
                if(count!=0)
                    tempString.append(",");
                tempString.append("\"");
                tempString.append(key);
                tempString.append("\"");
                tempString.append(":");
                String temp = jsonObject.get(key).toString();
                temp = temp.substring(1);
                temp = temp.substring(0,temp.length()-2);
                tempString.append(temp);
                tempString.append("\"");
                count++;
            }
            tempString.delete(tempString.length()-1,tempString.length()-1);
            tempString.append("}");
            return tempString.toString();
    }
}

I also tried using AsyncTask but I couldn't make it work.我也尝试过使用 AsyncTask 但我无法让它工作。

public class LoginAsync extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {

        String tempurl = "https://radiant-bayou-97811.herokuapp.com" + "/api/user/login/" + "user" + "/" + "test";
        JSONObject jsonObject = getRequest(tempurl);
        System.out.println(jsonObject);
        System.out.println(tempurl);

        if (jsonObject.has("login")) {
            try {
                if (jsonObject.get("login").equals("true"))
                    return 1L;
                else
                    return 0L;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        else
            return 0L;
        return 0L;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
          System.out.println("something");
        }

Then I just call the LoginAsync with some random url.然后我只是用一些随机的 url 调用 LoginAsync。 I can't understand what I'm doing wrong.我不明白我做错了什么。

Works fine on... whatever ... but not... Android ...工作正常......无论如何......但不是...... Android ...

If the error only occurs while running code on Android Device (or emulated Device from Android Studio IDE) this hints that something with your android permission settings might be missing...如果仅在 Android 设备(或来自 Android Studio IDE 的模拟设备)上运行代码时发生错误,则这暗示您的 android 权限设置可能丢失...

have you added <user-permission android:name="android.permission.INTERNET" /> to your AndroidManifest.xml?您是否已将<user-permission android:name="android.permission.INTERNET" />添加到您的 AndroidManifest.xml 中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM