来自Android设备的http请求

时间:2016-09-30 11:07:42

标签: android

使用java从Android设备执行http请求的最佳方法是什么? 清单中需要做哪些更改?

1 个答案:

答案 0 :(得分:1)

您可以使用HttpUrlConnectionOkHttp

在Android应用程序中调用您正在调用的任何api作为网址

首先,请求访问网络的权限,在清单中添加以下内容:

<uses-permission android:name="android.permission.INTERNET" />

以下AsyncTask将用于在单独的线程中调用http get方法api:

class RequestTask extends AsyncTask<String, String, String>{
    String server_response;

    @Override
    protected String doInBackground(String... uri) {
     URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(uri[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}


// Converting InputStream to String

private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }


To call this class you have to write:    new RequestTask ().execute("http://10.0.0.3/light4on");