从Web服务检索JSON - Java [服务不工作 - 现在正在工作]

时间:2014-09-16 18:41:16

标签: 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[] 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文本,但我没有得到任何东西,也没有错误。我的代码是错误的,或者此服务无效,还是其他什么......?

1 个答案:

答案 0 :(得分:0)

我总是建议使用gson。这将简化您的生活,因为只需一行就可以解析您的JSON并将其存储在Object 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; 
}

然后,你得到的反应就像这样解析:

User u = new GsonBuilder.create().fromJson(httpResponseFromServer, User.class);

然后你去了一个带有你的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));

如果问题仍然存在且您仍然得到空响应,则应该检查服务器端代码或连接。