来自Android设备的HTTP请求

俄语

使用Java从Android设备发出HTTP请求的最佳方法是什么?清单中需要进行哪些更改?

安贾利

您可以使用HttpUrlConnectionOkHttp在android应用程序中调用要作为url调用的任何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");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章