Http get request in Android 2.3.3

前端 未结 4 1455
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 09:16

I need help with sending HTTP GET request. My code is as follows:

    URL connectURL = new URL(\"url\");
    HttpURLConnection conn = (HttpURLCo         


        
4条回答
  •  悲&欢浪女
    2021-01-03 09:48

    I am using this piece of code for GET response which is working fine on my end:

    HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(requestUrl);
    
        HttpResponse response=null;
        try {
            response = client.execute(request);
        } catch (ClientProtocolException e) {
            Log.d(TAG,"1. "+e.toString());
    
        } catch (IOException e) {
            Log.d(TAG,"2. "+e.toString());
    
        }
        int status_code=response.getStatusLine().getStatusCode();
        Log.d(TAG,"Response Code returned ="+status_code);
    
        BufferedReader in=null;
        try {
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        } catch (IllegalStateException e) {
            Log.d(TAG,"3. "+e.toString());
        } catch (IOException e) {
            Log.d(TAG,"4. "+e.toString());
        }
    
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String newline = System.getProperty("line.separator");
        try {
            while ((line = in.readLine()) !=null){
                sb.append(line + newline);
            }
            String data = sb.toString();
            Log.d(TAG,data);
        } catch (IOException e) {
            Log.d(TAG,"5. "+e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.d(TAG,"6. "+e.toString());
        }
        String data = sb.toString();
    
        try {
            if(status_code==200 || status_code==401){
                JSONObject responseJSONObject = new JSONObject(data);
                responseJSONObject.put("tpg_status_code", status_code);
            }
        } catch (JSONException e) {
            Log.d(TAG,"6. "+e.toString());
        }
    

提交回复
热议问题