2013-03-22 74 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(); 

}