簡體   English   中英

從Web服務檢索JSON-Java [服務無法正常工作-現在正在工作]

[英]Retrieve JSON from web service - Java [Service was not working - NOW IS WORKING]

我想使用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文本,但我什么也沒有得到,也沒有錯誤。 我的代碼是否錯誤,或者此服務無法正常工作,或者其他原因...?

我總是建議使用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));

如果問題仍然存在,而您仍然得到一個空響應,則可能應該檢查服務器端代碼或連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM