2011-07-21 44 views
6

我已经在发送HTTP POST的Objective-C的发送方法和身体我把一个字符串:HTTP POST随着身体

NSString *requestBody = [NSString stringWithFormat:@"mystring"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]]; 
现在

在Android的我想要做同样的事情,我找一种设置http post的主体的方法。

回答

4

您可以使用此片段 -

HttpURLConnection urlConn; 
URL mUrl = new URL(url); 
urlConn = (HttpURLConnection) mUrl.openConnection(); 
... 
//query is your body 
urlConn.addRequestProperty("Content-Type", "application/" + "POST"); 
if (query != null) { 
urlConn.setRequestProperty("Content-Length", Integer.toString(query.length())); 
urlConn.getOutputStream().write(query.getBytes("UTF8")); 
} 
+0

以及我如何将urlconnection连接到http post? – MTA

+0

我已在上面添加更多代码以帮助您 – Suchi

+6

我认为需要添加:'urlConn.setDoOutput(true);' –

8

您可以使用HttpClient和HttpPost来构建和发送请求。

HttpClient client= new DefaultHttpClient(); 
HttpPost request = new HttpPost("www.example.com"); 

List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
pairs.add(new BasicNameValuePair("paramName", "paramValue")); 

request.setEntity(new UrlEncodedFormEntity(pairs)); 
HttpResponse resp = client.execute(request); 
+0

client.setEntity应该是request.setEntity – Gorky

6

可以使用HttpClientHttpPost尝试这样的事:

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("mystring", "value_of_my_string")); 
// etc... 

// Post data to the server 
HttpPost httppost = new HttpPost("http://..."); 
httppost.setEntity(new UrlEncodedFormEntity(params)); 

HttpClient httpclient = new DefaultHttpClient(); 
HttpResponse httpResponse = httpclient.execute(httppost); 
0
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

则每对

添加元素
nameValuePairs.add(new BasicNameValuePair("yourReqVar", Value); 
nameValuePairs.add(.....); 

然后使用HttpPost:

HttpPost httppost = new HttpPost(URL); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

,并使用HttpClientResponse得到来自服务器的响应

1

可以使用的HttpClient和HttpPost发送一个JSON字符串作为体:

public void post(String completeUrl, String body) { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(completeUrl); 
    httpPost.setHeader("Content-type", "application/json"); 
    try { 
     StringEntity stringEntity = new StringEntity(body); 
     httpPost.getRequestLine(); 
     httpPost.setEntity(stringEntity); 

     httpClient.execute(httpPost); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

的Json体例如:

{ 
    "param1": "value 1", 
    "param2": 123, 
    "testStudentArray": [ 
    { 
     "name": "Test Name 1", 
     "gpa": 3.5 
    }, 
    { 
     "name": "Test Name 2", 
     "gpa": 3.8 
    } 
    ] 
} 
+0

感谢@Guillaume编辑json格式 – NNguyen