问题描述
我有一些问题,应该是一个相当简单的任务。我只需要一个JSON数组,其中一个JSON对象就可以发布到我的webservice中。整个网址请求的格式如下: {key1:val1,key2:val2。 ...}]
我无法为我的生活找出如何使用HttpPost附加location_data位。
这是一个代码片段来演示我使用的HTTP连接方法:
HttpClient hClient = new DefaultHttpClient();
HttpPost hPost = new HttpPost(url);
try {
hPost.setEntity(new StringEntity(string));
hPost.setHeader(Accept,application / json);
hPost.setHeader(Content-type,application / json);
//执行请求
HttpResponse response =(HttpResponse)hClient.execute(hPost);
HttpEntity entity = response.getEntity();
我没有任何语法错误,我的代码正在访问服务器,只是不在服务器需要的确切格式。任何帮助如何格式化我的请求,看起来像我需要它将非常感谢!
附加键/值数据在?不是POST之后的URL。
这是如何在Java中POST数据:
String urlText =http://www.myserver.com/myservice.php;
String postContent =location_data = [{\key1\:\val1\,\key2\:\val2 \}]
try {
HttpURLConnection c =(HttpURLConnection)new URL(urlText).openConnection();
c.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream(),UTF-8);
writer.write(postContent);
writer.close();
} catch(IOException e){
e.printStackTrace();
}
I am having some problems with what should be a rather simple task. I simply need a JSON array with a single JSON object within it to be posted to my webservice. The entire URL request needs to be formatted like this:
http://www.myserver.com/myservice.php?location_data=[{"key1":"val1","key2":"val2"....}]
I cannot for the life of me figure out how to append the 'location_data' bit using HttpPost.Here is a code snippet to demonstrate the HTTP connection method I am using:
HttpClient hClient = new DefaultHttpClient();
HttpPost hPost = new HttpPost(url);
try {
hPost.setEntity(new StringEntity(string));
hPost.setHeader("Accept", "application/json");
hPost.setHeader("Content-type", "application/json");
//execute request
HttpResponse response = (HttpResponse) hClient.execute(hPost);
HttpEntity entity = response.getEntity();
I don't have any syntax errors, and my code is accessing the server fine, just not in the exact format the server needs. Any help on how to format my request to look like how I need it would be greatly appreciated!
Appending key/value data to URLs after a '?' is GET not POST.
This is how to POST data in Java:
String urlText = "http://www.myserver.com/myservice.php";
String postContent = "location_data=[{\"key1\":\"val1\",\"key2\":\"val2\"}]";
try {
HttpURLConnection c = (HttpURLConnection) new URL(urlText).openConnection();
c.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream(), "UTF-8");
writer.write(postContent);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
这篇关于在Android中将JSON数组发布到webservice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!