发送JSON以寻址并检索响应

时间:2013-09-18 08:44:54

标签: java android json

这个问题肯定是重复的,但我需要一个答案而无法找到答案。

我需要将一个Json json对象发送到服务器并检索另一个json。 到目前为止我所尝试的并没有奏效,没有任何反应。

我做错了什么?

要发送的json对象是userCreate,地址是path,告诉我你是否真的需要地址和json格式。

解决,最终代码:

Thread x = new Thread(){
                        public void run(){
                            Looper.prepare();
                            DefaultHttpClient client = new DefaultHttpClient();
                            HttpPost post = new HttpPost(path);
                            String result = "";
                            try {        
                                post.setEntity(new StringEntity(userCreate.toString())); 
                                HttpResponse response = client.execute(post);                               
                                HttpEntity entity = response.getEntity();
                                result = EntityUtils.toString(entity);
                                Toast.makeText(ctx,"Result: " + result + " response: " + response.getStatusLine().getStatusCode(), 10000).show();             
                            } catch(Exception e) {
                                e.printStackTrace();
                            }
                            Looper.loop();
                        }
                    };
                    x.start();

4 个答案:

答案 0 :(得分:2)

尝试:

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(request.toString(), "utf-8")); 
                                // request is the JSONObject
HttpResponse response = client.execute(post);

答案 1 :(得分:1)

这对我有用:

//MainActivity.java
Pass the name-value pair to server .you can get those values using json-array in PHP.


String registerURL="http:10.0.2.2/register.php";

public void registerUser(String email, String password, String mobile)
 {

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    params.add(new BasicNameValuePair("mobile", mobile));



 JsonParser.makeHttpRequest(registerURL,"POST",params);




}

//JSONParser.java

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public static JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {


    // 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);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();



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


            // request method is 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) {

    }

    // try parse the string to a JSON object
    try {

        jObj = new JSONObject(json);

    } catch (JSONException e) {

    }

    // return JSON String
    return jObj;

}
}

答案 2 :(得分:0)

尝试类似:

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
post.setEntity(new StringEntity(request.toString(), "utf-8"));
HttpResponse response = client.execute(post);

跳这将有所帮助。

答案 3 :(得分:0)

这对我有用:

// General query of the website. Takes an object of type Q and returns one of class R.
public static <Q extends JSONObject, R> R query(String urlBase, String op, Q q, Class<R> r) throws IOException {
  // Prepare to post.
  final HttpPost postRequest = new HttpPost(urlBase + op);

  if (q != null) {
    // Get it all into a JSON string.
    final StringEntity input = new StringEntity(asJSONString(q));
    input.setContentType("application/json");
    postRequest.setEntity(input);
  }
  log.debug("> " + urlBase + op + (q == null ? "" : " " + q));
  // Post it and wait.
  return readResponse(postRequest, HttpClientPool.getClient().execute(postRequest), r);
}