从web服务中检索JSON-Java[服务未工作-现在工作]
我想使用POST方法从web服务获取JSON。这是我的代码,我已经试过了:从web服务中检索JSON-Java[服务未工作-现在工作],java,json,web-services,http-post,Java,Json,Web Services,Http Post,我想使用POST方法从web服务获取JSON。这是我的代码,我已经试过了: public class Test { public static void main(String[] args) { String urlStr = "http://dev.crnobelo.mk/web_services/index.php/index/horoscope"; String[] paramName = { "horoscope_sign" }; String[] para
public class Test {
public static void main(String[] args) {
String urlStr = "http://dev.crnobelo.mk/web_services/index.php/index/horoscope";
String[] paramName = { "horoscope_sign" };
String[] paramVal = { "oven" };
try {
String output = httpPost(urlStr, paramName, paramVal);
System.out.println("Result: " + output);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
// writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
}
所以,我应该得到JSON文本,但我什么也没有得到,也没有错误。是我的代码错了,还是这项服务不起作用,还是其他什么…?我总是建议使用gson。这将简化您的生活,因为只需一行代码,您就可以解析JSON并将其存储在对象EJ中:
{
"key_1" : "name",
"key_2" : "last_name",
"friends" : [
"jhon", "devorah", "charles"
]
}
类属性是这样的
public class User {
public String key_1;
public String last_name;
ArrayList<String> friends;
}
这就是一个完全填充了Json数据的对象
这段代码属于我的utils.java,我将它添加到我的每个项目中。这将为您提供来自http服务器的响应。希望能有帮助
public static String getStrResponse(String url, List<NameValuePair> params) {
try {
HttpClient httpclient = createHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = params;
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
in));
StringBuffer str = new StringBuffer();
String line = null;
while ((line = bReader.readLine()) != null) {
str.append(line);
}
return str.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "FALSE";
}
使用它,就像这样
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("mensaje", message));
nameValuePairs.add(new BasicNameValuePair("id_from", id_from));
nameValuePairs.add(new BasicNameValuePair("id_to", id_to));
Log.v("RESPONSE", utils.getStrResponse(yourUrl, nameValuePairs));
如果问题仍然存在,并且您仍然得到一个空响应,您可能应该检查服务器端代码或密码。您是否尝试设置conn.setDoInputtrue;我又加了一句,但还是一样的……空白结果:/n你不需要做一个conn.connect;在某个时候?具体来说,在设置所有连接参数之后,但在请求输入流之前,服务器似乎会返回空白页。我用RESTClient Firefox插件测试了它,它返回blank@iTech也许您没有使用正确的POST变量调用webservice.gson是一个很好的建议,但这并没有真正回答他手头的问题。我认为他的主要问题是服务器没有使用他期望的JSON响应进行响应。我不认为他真的在请求帮助解析他没有得到的JSON响应。在这种情况下,他应该问如何在服务器端创建JSON对象,而不是我想使用POST方法从web服务获取JSON。我编辑了我的答案,以提供一个最完整的客户端解决方案。是的,正如他们所说,我可能在服务器或向服务器发送post req方面有问题,而不是在解析数据方面。如果您可以添加服务器端代码,这会有所帮助。尝试使用我提供的getStrResponse方法。我知道这很有效。如果答案仍然为空,则错误肯定在其他地方。
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("mensaje", message));
nameValuePairs.add(new BasicNameValuePair("id_from", id_from));
nameValuePairs.add(new BasicNameValuePair("id_to", id_to));
Log.v("RESPONSE", utils.getStrResponse(yourUrl, nameValuePairs));