2012-05-11 120 views
0

我嘗試了很多不同的方法來獲得http響應,但總是得到消息null。我嘗試使用chrome附帶的Advance Rest Client工具。在那裏,我得到了成功的迴應。我不知道我在做錯什麼。HttpURLConnection,HttpClient和HttpPost請求在Android中不能與POST請求一起工作

try { 

     String urlParameters = "id=userid&password=password&device=android"; 

     URL url = new URL("my url"); 
     HttpURLConnection urlConnection = (HttpURLConnection) url 
       .openConnection(); 

     urlConnection.setRequestMethod("POST"); 
     urlConnection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 

     urlConnection.setRequestProperty("Content-Length", 
       "" + Integer.toString(urlParameters.getBytes().length)); 
     urlConnection.setRequestProperty("Content-Language", "en-US"); 

     urlConnection.setUseCaches(false); 
     urlConnection.setDoInput(true); 
     urlConnection.setDoOutput(true); 

     OutputStream outputStream = urlConnection.getOutputStream(); 
     outputStream.write(urlParameters.getBytes()); 
     outputStream.close(); 

     int responseCode = urlConnection.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      InputStream in = urlConnection.getInputStream(); 
      resultstring = convertinputStreamToString(in); 
      Log.d("Result String-------->", resultstring); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

我附上截圖在那裏我得到的結果是:成功 但在上面的代碼中,我得到的結果:失敗

enter image description here

我一直在使用的HttpClient和HttpPost也試過代碼。但這也doent工作

try { 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(
       "my url"); 

     httpPost.setHeader("Accept", "application/json"); 
     httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 
     nameValuePairs.add(new BasicNameValuePair("id", "userid")); 
     nameValuePairs.add(new BasicNameValuePair("password", "password")); 
     nameValuePairs.add(new BasicNameValuePair("device", "android")); 

     // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     UrlEncodedFormEntity se = new UrlEncodedFormEntity(nameValuePairs); 
     se.setContentType("application/x-www-form-urlencoded"); 
     httpPost.setEntity(se); 
     httpPost.getParams().setBooleanParameter(
       "http.protocol.expect-continue", false); 

     HttpResponse response = client.execute(httpPost); 

     String responseAsText = EntityUtils.toString(response.getEntity()); 
     Log.d("Result String-------->", responseAsText); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

請幫我。我嘗試了幾乎所有的東西。

回答

-1
HttpClient localHttpClient = this.app2.getHttpClient(); 
    HttpPost localHttpPost = new HttpPost("yourURL.com"); 
    localHttpPost.setEntity(new UrlEncodedFormEntity(myArrayList)); 
    InputStream localInputStream = localHttpClient.execute(localHttpPost).getEntity().getContent(); 

嘗試類似這樣的東西。 您必須將響應作爲輸入流讀取,然後在返回結果後執行您的工作。

此外,一定要檢查服務器,因爲它可能沒有按預期返回響應。