Android HTTP PUT 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3649814/
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
Android HTTP PUT Request
提问by peterlawn
Can anyone give me a HTTP PUTrequest example code for Android?
谁能给我一个HTTP PUTAndroid的请求示例代码?
回答by BeRecursive
Assuming you want to use an HttpURLConnection, to perform an HTTP PUT you use the following:
假设您要使用 HttpURLConnection,要执行 HTTP PUT,请使用以下命令:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Data you want to put");
out.close();
To use the HTTPPut class then try:
要使用 HTTPPut 类,请尝试:
URL url = new URL("http://www.example.com/resource");
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
I'm pretty sure this should work though I haven't tested it :)
我很确定这应该有效,尽管我还没有测试过:)
回答by Sheharyar
It's better to use a library like Android Async HTTPor Volleythat take the complexity out of networking and make it easier to handle request responses. This is how you would do it with AsyncHTTP:
最好使用类似Android Async HTTP或Volley这样的库,以消除网络的复杂性并使处理请求响应更容易。这是您使用 AsyncHTTP 的方式:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("some_key", "value-1");
params.put("another_key", "value-2");
client.put(url, params, new AsyncHttpResponseHandler {
public void onSuccess(int statusCode, Header[] headers, String response) {
// Do something with response
}
});

