尝试解析json对象时出错

时间:2015-07-31 11:08:17

标签: android json

public class JSONParser {
   static InputStream is = null;
   static JSONObject jObj = null;
   static String json = "";
   static InputStream iStream = null;
   static JSONArray jarray = null;


   // constructor
    public JSONParser() {

   }
  public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {


      try {

         // check for request method
         if(method == "POST"){
            // request method is POST
            // 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();

            }
             else 
               if(method == "GET"){

               DefaultHttpClient httpClient = new DefaultHttpClient();
               String paramString = URLEncodedUtils.format(params, "utf-8");
               url += "?" + paramString;
               HttpGet httpGet = new HttpGet(url);

               HttpResponse httpResponse = httpClient.execute(httpGet);
               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();
    } 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;

}
/////////////////////////////////
public JSONArray getJSONFromUrl(String url) {

       StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine();
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
          } else {
            Log.e("==>", "Failed to download file");
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }

    // Parse String to JSON object
    try {
        jarray = new JSONArray( builder.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jarray;

}


public JSONObject makeHttpRequest2(String url) {

    // Making HTTP request
    try {

        // check for request method
        //if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            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();
    } 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;}}

Androidside代码

JSONParser jParser = new JSONParser();

JSONObject json;
private static String url = "http://localhost:8888";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    submit=(Button)findViewById(R.id.button1);

     submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
    // execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL 
        //and get output response from InputStream and return it.
                new Login().execute();

            }
        });


}
  private class Login extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... args) {
            // Getting username and password from user input
            String username = "Hello";


            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id0",username));

            json = jParser.makeHttpRequest(url, "GET", params);
            String s=null;      



            return null;
        }

    }

我想将json对象发送到服务器。程序中没有错误。 但是当我尝试运行程序时,android应用程序停止工作。 单击“提交”按钮时出现错误。 感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

当你有AsyncTask&lt;字符串,字符串,字符串&gt;当你打电话给asynTask

时,你应该通过第一个argumnet
new Login().execute(url);

您已在代码中定义了网址