如何向Android中的webservice发送请求?

时间:2011-09-10 10:36:00

标签: android django web-services

我在django中写了一个web服务

如果我使用像这样的终端命令

curl --dump-header - -H "Content-Type: application/json" -X PUT
    --data '{"name": "Change","address": "/api/v1/user/1/"}' 
    http://localhost:8000/api/items/1/

如何将命令写入Android请求到webservice?

1 个答案:

答案 0 :(得分:2)

这应该这样做:

HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);

HttpClient httpClient = new DefaultHttpClient(myParams);
HttpContext localContext = new BasicHttpContext();
HttpPut httpPut = new HttpPut("http://localhost:8000/api/items/1/");
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-Type", "application/json");

String data = // put your JSON object here
tmp = new StringEntity(data, "UTF-8");

httpPut.setEntity(tmp);
response = httpClient.execute(httpPut, localContext);

Srting result = EntityUtils.toString(response.getEntity());