开发者

Android HTTP PUT Request

开发者 https://www.devze.com 2023-01-15 03:28 出处:网络
Can anyone give me a HT开发者_开发百科TP PUT request example code for Android?Assuming you want to use an HttpURLConnection, to perform an HTTP PUT you use the following:

Can anyone give me a HT开发者_开发百科TP PUT request example code for Android?


Assuming you want to use an HttpURLConnection, to perform an HTTP PUT you use the following:

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:

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 :)


It's better to use a library like Android Async HTTP or Volley that take the complexity out of networking and make it easier to handle request responses. This is how you would do it with 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
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消