问题
Hi I am developing small android application in which I want to use HttpUrlConnection post request with params as json object. But its not working for me I did it in following way:
try 
{
    URL url;
    DataOutputStream printout;
    DataInputStream  input;
    url = new URL ("https://abc.com");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");  
    urlConnection.setDoInput (true);
    urlConnection.setDoOutput (true);
    urlConnection.setUseCaches (false);
    urlConnection.setConnectTimeout(10000);  
    urlConnection.setReadTimeout(10000);
    urlConnection.setRequestProperty("Content-Type","application/json");   
    urlConnection.connect();  
    JSONObject jsonParam = new JSONObject();
      JSONArray arr = new JSONArray();
      arr.put("LNCf206KYa5b");
      arr.put("oWdC0hnm1jjJ");
      jsonParam.put("places", arr);
      jsonParam.put("action", "Do");
            printout = new DataOutputStream(urlConnection.getOutputStream ());
            printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
            printout.flush ();
            printout.close ();
            int HttpResult =urlConnection.getResponseCode();  
        if(HttpResult ==HttpURLConnection.HTTP_OK){  
        BufferedReader br = new BufferedReader(new InputStreamReader(  
            urlConnection.getInputStream(),"utf-8"));  
        String line = null;  
           while ((line = br.readLine()) != null) {  
            sb.append(line + "\n");  
        }  
        br.close();  
           //System.out.println(""+sb.toString());  
        }else{  
             System.out.println(urlConnection.getResponseMessage());  
        }  
    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    }  
    catch (IOException e) {  
        e.printStackTrace();  
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{  
        if(urlConnection!=null)  
           urlConnection.disconnect();  
    }  
}
Its not giving any response code or any output. Am I doing something wrong. How to slove this problem. Need help. Thank you .
I got following system error
06-07 09:55:58.171: W/System.err(4624): java.io.IOException: Received authentication challenge is null
06-07 09:55:58.171: W/System.err(4624):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:1153)
06-07 09:55:58.171: W/System.err(4624):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:1095)
06-07 09:55:58.171: W/System.err(4624):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1048)
06-07 09:55:58.171: W/System.err(4624):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:726)
06-07 09:55:58.179: W/System.err(4624):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:121)
06-07 09:55:58.179: W/System.err(4624):     at com.mobiotics.qcampaigns.data.operation.ProximityOperation.execute(ProximityOperation.java:187)
06-07 09:55:58.179: W/System.err(4624):     at com.foxykeep.datadroid.service.RequestService.onHandleIntent(RequestService.java:145)
06-07 09:55:58.179: W/System.err(4624):     at com.foxykeep.datadroid.service.MultiThreadedIntentService$IntentRunnable.run(MultiThreadedIntentService.java:170)
回答1:
This error occurs due to 401 responsecode.
You can check first response code like this
int responsecode = response.getStatusLine().getStatusCode();
This exception is thrown if the server replies with a 401.
The actual cause for the 401 that you didn't send an OAuth verifier code where it was expected at this point.
You can refer below code
    String url = LoginUrl;
    String resultstring = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
    nameValuePairs.add(new BasicNameValuePair("j_username", username));
    nameValuePairs.add(new BasicNameValuePair("j_password", password));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                Util.cookieStore);
        try {
            HttpResponse response = httpclient.execute(httppost,
                    localContext);
            int responsecode = response.getStatusLine().getStatusCode();
            if (responsecode == 200) {
                Util.responsecode = responsecode;
                resultstring = "Success";
                InputStream in = response.getEntity().getContent();
                resultstring = Util.convertinputStreamToString(in);
            } else if (responsecode == 401) {
                Util.responsecode = responsecode;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
回答2:
I higly recommend using Unirest its a simple library for making http requests it has a very easy to use api and it doesnt overload the mem too much, here's an example on how would it be using your example code.
Unirest.post("https://example.com")
.queryString("places", "['LNCf206KYa5b', 'oWdC0hnm1jjJ']")
.queryString("action", "Do")
.asJson()
来源:https://stackoverflow.com/questions/16976240/httpurlconnection-with-post-request-and-parameter-as-json-object-android