2013-03-22 75 views
2

我創建android的一個HttpURLConnection類,並準備好應對後如下圖所示HTTP POST HTTPUrlConnection中的數據未設置?

urlConnection = (HttpURLConnection) url.openConnection(); 

urlConnection.setRequestProperty("content-type", "application/json"); 
byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"), Base64.DEFAULT); 
//Basic Authorization    
urlConnection.setRequestProperty("Authorization", "Basic "+ new String(encoded, "UTF-8")); 
urlConnection.setDoInput(true); 
urlConnection.setDoOutput(true); 

//This gets implicitly set when DoOutput is True, but still let it be    
urlConnection.setRequestMethod("POST"); 

//Required for POST not to return 404 when used on with a host:port combination 
//http://stackoverflow.com/questions/5379247/filenotfoundexception-while-getting-the-inputstream-object-from-httpurlconnectio 
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0"); 
urlConnection.setRequestProperty("Accept","*/*"); 

然後,我準備JSON,並將其寫入到連接

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("key1", "value1"); 
jsonObject.put("key2", "value2"); 



outputStreamWriter = urlConnection.getOutputStream(); 
outputStreamWriter.write(jsonObject.toString().getBytes()); 


finally { 
    if (outputStreamWriter != null) try { outputStreamWriter.close(); } catch (IOException logOrIgnore) {} 
      } 

OutputStream當我這樣做請求,我得到500的狀態,因爲我的服務器收到一個空的POST數據,這是無效的json。

從Web瀏覽器和捲曲相同的作品。 GET在Android上使用相同的參數。我錯過了什麼? POST請求應該設置的參數方式的順序有問題嗎?

+0

您的服務器是否收到請求的其餘部分? (auth,用戶代理?) – njzk2 2013-03-22 14:01:50

+0

<使用權限android:name =「android.permission.INTERNET」/> – 2013-03-22 14:03:16

+0

@ njzk2 - 是的,它確實 – 2013-03-22 14:08:27

回答

1

我能夠得到這個工作。從下面

創建數據的代碼片段被髮送,注意需要

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 

nameValuePairs.add(new BasicNameValuePair("\A\"", "\"/api/v1/a/1/\"")); 

nameValuePairs.add(new BasicNameValuePair("\"B\"", "\"/api/v1/b/1/\"")); 

nameValuePairs.add(new BasicNameValuePair("\"C\"", "\"Hello from Android\"")); 

創建客戶端,並設置頭

HttpClient httpclient = new DefaultHttpClient(); 

HttpPost httppost = new HttpPost(urlToPost); 

httppost.setHeader("content-type", "application/json"); 

設置授權的轉義引號標題

String encoded = "Basic " + Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP); 

httppost.setHeader("Authorization",encoded); 

字符串的數據,並把它設置爲HTTP參數在POST請求

StringEntity entity = new StringEntity(getQueryJSON(nameValuePairs)); 

httppost.setEntity(entity); 

HttpResponse response = httpclient.execute(httppost); 

if(response!=null){ 

InputStream in = response.getEntity().getContent(); //Get the data in the entity 

readStream(in); 

} 

效用函數JSON編碼爲字符串 私人字符串getQueryJSON(列表PARAMS)拋出UnsupportedEncodingException

{ 

    StringBuilder result = new StringBuilder(); 

    boolean first = true; 

    for (NameValuePair pair : params) 

    { 

    if (first){ 

     first = false; 

     result.append("{"); 

    }else 

     result.append(","); 


    result.append(pair.getName()); 

    result.append(":"); 

    result.append(pair.getValue()); 


    } 

    result.append("}"); 

    return result.toString(); 

}