没有获得JSON响应

时间:2014-09-11 07:26:45

标签: android json

我有" POST"的以下代码请求在哪里,我有一个API和参数。 但是,在这里我没有得到任何回应也没有错误。请帮助我。

public JSONObject makeHttpRequest(String url, List<NameValuePair> params)       throws Exception {      
        // Making HTTP request
        try {
            Log.d("URL :", url);
            Log.d("params :", params.toString());
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
           Log.d("InputStreem :", is.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            Log.d("BufferedReader :", reader.toString());
                  StringBuilder sb = new StringBuilder();
                  String line = null;
                  while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                  }
                  is.close();
                  jsonResponse = sb.toString();
            System.out.println("Respose :"+jsonResponse);//Here Resonse: "nothing"
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        // try parse the string to a JSON object
        try {
            jsonData = new JSONObject(jsonResponse);
        } catch (JSONException e) {
            throw new Exception(e.getMessage());
        }
        // return JSON String
        return jsonData;
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

  1. 定义JSON-Class。例如:
  2. `

     public class JSONParser {
    
            static InputStream is = null;
            static JSONObject jObj = null;
            static String json = "";
    
            // constructor
            public JSONParser() {
    
            }
    
            public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
    
                // Making HTTP request
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    json = sb.toString();
                    Log.e("JSON", json);
                } catch (Exception e) {
                    Log.e("Buffer Error", "Error converting result " + e.toString());
                }
    
                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
    
                // return JSON String
                return jObj;
    
            } }
    
    1. 定义Functions-Class,其中包含您的应用程序与服务器通信所需的所有功能。例如:

      public class UserFunctions {

      private JSONParser jsonParser;
      
      // URL of the API
      private static String functionURL = "http://xxx.xxx.xxx.xx/.../";
      
      // TAG to determine which function/query should be executed on serverside
      // e.g. with IF-ELSE
      private static String function_tag = "getData";
      
      // Constructor
      public UserFunctions() {
          jsonParser = new JSONParser();
      }
      
      /**
       * FUNCTION GetSomeData
       **/
      
      // Here you can define functions, and give parameters (if you need)
      // and catch those on serverside with POST as their names
      // you defined in qoutes, in this example you could catch the 2 parameters
      // with
      // $email = $_POST['email']; and $password = $_POST['password']; (assumed
      // you use PHP)
      
      public JSONObject functionGetData(String parameter1, String parameter2) {
          // Building Parameters
          List<NameValuePair> params = new ArrayList<NameValuePair>();
          params.add(new BasicNameValuePair("tag", function_tag));
          params.add(new BasicNameValuePair("email", parameter1));
          params.add(new BasicNameValuePair("password", parameter1));
          JSONObject json = jsonParser.getJSONFromUrl(functionURL, params);
          return json;
      }}
      
    2. 使用AsynchTask获取json数据。例如:

      私有类FetchDataTask扩展             AsyncTask {

          String parameter1, parameter2;
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              // Define variables here (if needed), that will be commited to
              // function/method in
              // doInBackground() as parameters
      
          }
      
          @Override
          protected JSONObject doInBackground(String... args) {
      
              UserFunctions userFunction = new UserFunctions();
      
              JSONObject json = userFunction.functionGetData(parameter1,
                      parameter2);
      
              return json;
      
          }
      
          @Override
          protected void onPostExecute(JSONObject json) {
      
              try {
      
                  // Catch data from JSON
                  // Create JSON object and get it by calling method
                  // getString("data")
                  // on serverside json:
                  // $response["jsonObj"]["data"] = $SQL_result['columnXY'];
      
                  JSONObject json_object = json.getJSONObject("jsonObj");
      
                  String data = json_object.getString("data");
      
              } catch (JSONException e) {
                  e.printStackTrace();
      
              }
      
          }}
      
    3. 希望它有所帮助。