如何调用和获取 json 网络服务?

How to call and get json webservice?

我有一个问题,当我尝试获得响应时,我的代码被停止了。

public String JCon() {

    StringBuilder strcon = new StringBuilder();
    strcon.append("{");
    strcon.append(" \"username\":\"aaaaaaaa\",");
    strcon.append("\"password\":\"1\",");
    strcon.append("\"device_type\":\"ANDROID\",");
    strcon.append("\"device_token\":\"1234567890\"");
    strcon.append("}");


    HttpClient httpC = new DefaultHttpClient();
    HttpPost httpP = new HttpPost(
            "http://203.162.10.112:8080/ezcheck/rest/user/login");
    JSONObject jcon;
    try {
        jcon = new JSONObject(strcon.toString());
        httpP.setEntity(new StringEntity(jcon.toString()));

        // error in here
        HttpResponse httpR = httpC.execute(httpP);

    } catch (JSONException e1) {
        return "Can't creat Json";
    } catch (UnsupportedEncodingException e) {
        return "UnsupportedEncodingException";
    } catch (ClientProtocolException e) {
        return "ClientProtocolException";
    } catch (IOException e) {
        return "IOException";
    }
}

这是我尝试测试连接并从网络服务获取响应的代码。我找不到任何异常,所以我不明白什么是问题,我只知道我的问题出在 HttpResponse httpR = httpC.execute(httpP);

您不能在主线程上打开 http 或其他网络连接,这会导致致命异常 NetworkOnMainThreadException。 如果在 IDE 中没有观察到任何异常,请打开 command line 并键入:

adb logcat "*:E"

您会看到异常。

在您的代码中试试这个:

new Thread(new Runnable(){
    JCon();
});

那就可以了,不过我建议用HandlerAsynctask代替Thread

你可以使用我的代码:

private  class get_txt_from_url extends AsyncTask<String , Void , String>{
        final String TAG = "get_txt_from_url";


        @Override
        protected String doInBackground(String... params) {

            InputStream is = null;
            BufferedReader reader = null;
            StringBuilder string_builder = null;
            String line ="";


            try {
                HttpClient hc = new DefaultHttpClient();
                HttpPost hp = new HttpPost(params[0]);
                HttpResponse hr = hc.execute(hp);
                HttpEntity htity = hr.getEntity();
                is = htity.getContent();
            } catch (IOException e) {
               Log.d(TAG , "ZERO");
            }

            try {
                reader = new BufferedReader(new InputStreamReader(is , "utf-8") , 8);
                string_builder = new StringBuilder();
            } catch (UnsupportedEncodingException e) {
                Log.d(TAG, "ONE");
            }


            try {
                while((line = reader.readLine()) != null){
                    string_builder.append(line+"");
                }
            } catch (IOException e) {
                Log.d(TAG, "line");
            }


            return string_builder.toString();
        }

        @Override
        protected void onPostExecute(String s) {

            Log.d(TAG , s);

        }
    }

AND ... 要使用您需要执行此操作的方法:

new get_txt_from_url().execute(the url String/*Example:  http://www.google.com*/);

你会在日志猫中看到它。