我已经发送了在发送http帖子的objective-c中的方法,并在正文中我放了一个字符串:
NSString *requestBody = [NSString stringWithFormat:@"mystring"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];
Run Code Online (Sandbox Code Playgroud)
现在在Android我想做同样的事情,我正在寻找一种方法来设置http帖子的正文.
Jus*_*yul 13
您可以使用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);
Run Code Online (Sandbox Code Playgroud)
你可以使用这个片段 -
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"));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用HttpClient和HttpPost尝试这样的事情:
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);
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
Json身体示例:
{
"param1": "value 1",
"param2": 123,
"testStudentArray": [
{
"name": "Test Name 1",
"gpa": 3.5
},
{
"name": "Test Name 2",
"gpa": 3.8
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85124 次 |
| 最近记录: |