我已经在发送HTTP帖子的Objective-C中发送了方法,并且在正文中放置了一个字符串:

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

现在在Android中,我想做同样的事情,我正在寻找一种设置http帖子正文的方法。

最佳答案

您可以使用此代码段-

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"));
}

07-27 13:34