Java Android向restful Web服务发送数据
我正在尝试使用jersey库将数据从android智能手机发送到java制作的restful Web服务 我看到了以下关于如何做的答案:Java Android向restful Web服务发送数据,java,android,web-services,rest,http-post,Java,Android,Web Services,Rest,Http Post,我正在尝试使用jersey库将数据从android智能手机发送到java制作的restful Web服务 我看到了以下关于如何做的答案: public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursit
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
}
}
如果我有一个具有以下签名的Web服务:
@POST
@Path("/post/location")
@Consumes(MediaType.APPLICATION_JSON)
public Response createLocation(Loc location)
nameValuePairs
变量中的“id”
部分是什么,它是location还是Loc?试试这个
//
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或其他东西,而不仅仅是对应于表单数据的键值参数。使用什么技术构建您的web服务?Jersey 1.18库和genson反序列化对象在android上执行应用程序时会得到什么响应?什么错误?现在我的连接被拒绝了。但这是一个我希望看到答案的问题。您使用StringEntity,它将json对象以一种奇怪的格式放置在字符串中,格式为\“to allow for the”。我不想用它。我想发送一个json字符串,它是由Gsonso提供给我的,只需构建您自己的json?“{'id':'id','hi':'value'}”我可以完全正确地完成JSON部分,但是我怎么能只发送一个字符串呢?没有使用StringEntity还有其他方法吗?好的,这对我来说很有效,我用你的答案得出了最终的解决方案。谢谢。保存我的部分是reques.addHeader(“内容类型”、“应用程序/json”);我之前将其添加到StringEntity对象而不是postrequest
//
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);