Android 如何发送 HTTP POST 请求并接收响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3038409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send HTTP POST request and receive response?
提问by Maxim Kachurovskiy
I'm going to create mobile application that works with CommuniGate Pro server.
我将创建可与 CommuniGate Pro 服务器配合使用的移动应用程序。
For example, I need to make the following Android Client C
- CGP Server S
conversation and get XIMSS.nonce
node value:
例如,我需要进行以下 Android Client C
- CGP ServerS
对话并获取XIMSS.nonce
节点值:
C:GET /ximsslogin/ HTTP/1.1
Host: myserver.com
Content-Type: text/xml
Content-Length: 42
<XIMSS><listFeatures id="list" /><XIMSS>
S:HTTP/1.1 200 OK
Content-Length: 231
Connection: keep-alive
Content-Type: text/xml;charset=utf-8
Server: CommuniGatePro/5.3
<XIMSS><nonce>2C3E575E5498CE63574D40F18D00C873</nonce><language>german</language><response id="s"/></XIMSS>
Example, in ActionScript 3.0 it looks this way:
例如,在 ActionScript 3.0 中,它是这样的:
var loader:Loader = new Loader();
loader.addEventListener(Event.COMPLETE, completeHandler);
var urlRequest:URLRequest = new URLRequest(...);
urlRequest.method = ...;
urlRequest.data = ...;
loader.load(urlRequest);
private function completeHandler(...):void { ... };
How will it look in Java for Android 2.1?
它在Android 2.1 的Java 中看起来如何?
回答by Donal Rafferty
As Schnapple says your question seems very broad and is confusing to read and understand.
正如 Schnapple 所说,您的问题似乎非常广泛,阅读和理解令人困惑。
Here is some general code to send a HTTP POST and get a response from a server though that may be helpful.
这是一些发送 HTTP POST 并从服务器获取响应的通用代码,尽管这可能会有所帮助。
public String postPage(String url, File data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
FileEntity tmp = null;
tmp = new FileEntity(data,"UTF-8");
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}