我正在尝试将数据从Android智能手机发送到使用jersey库在java中创建的一个安静的网络服务。
我看到了如何做到以下答案:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
虽然这似乎是对的,但我对nameValuePairs
变量有疑问。
特别是在这一部分:
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
如果我的网络服务具有以下签名:
@POST
@Path("/post/location")
@Consumes(MediaType.APPLICATION_JSON)
public Response createLocation(Loc location)
"id"
变量中的nameValuePairs
部分是什么,它是位置还是Loc?。
答案 0 :(得分:1)
试试这个
//
String url = 'url_to_you_server_api.dev/postservice'
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
params.put("id","id");
params.put("hi","hi");
StringEntity jsonEntity = new StringEntity( params.toString() );
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type","application/json");
request.setEntity(jsonEntity);
response = client.execute(request);
如果你服务接收一个实体它可能是一个json或者不仅仅是与表单数据相对应的键值参数。