Android HTTP PUT请求

pet*_*awn 11 android

任何人都可以给我一个HTTP PUTAndroid 的请求示例代码吗?

BeR*_*ive 24

假设您要使用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();
Run Code Online (Sandbox Code Playgroud)

要使用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);
Run Code Online (Sandbox Code Playgroud)

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