Android HTTP PUT请求

时间:2010-09-06 07:50:08

标签: android

任何人都可以为我提供HTTP PUT请求示例代码吗?

2 个答案:

答案 0 :(得分:23)

假设您要使用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();

要使用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);

我很确定这应该可行但我还没有测试过:)

答案 1 :(得分:0)

最好使用Android Async HTTPVolley之类的库,这些库可以消除网络连接的复杂性,并使处理请求响应更容易。这就是使用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
  }
});