使用http,fedup和失败发布JSON

时间:2013-07-31 11:21:18

标签: android json http httprequest

我已经使用了大约5种方法将JSON数据发布到HTTP请求URL但它没有得到很好的结果,它没有发布我想要的JSON格式,以下是我想要发送的JSON以及我当前成功发送它使用HTML:

这是我想要的JSON: { “×”: “N”, “Y”: “55”}

这是我成功运作的HTML代码:

<html><head><script>
function sendForm(form)
{
      // Construct the JSON string in form.value
      // x is a string ('cos of the quotes)
      // y is an integer ('cos of no quotes)
      form.value.value = "{ \"x\": \"" + form.example1.value + "\", \"y\": " + form.example2.value + " }"
      form.submit();
}
</script></head>
<body>
<form action="https://api.winv.com/v1/4bhj/306adk" method="post">
<input type="hidden" name="value">
string:<input type="text" name="example1">
number:<input type="text" name="example2">
<input type="button" value="Submit" onClick="sendForm(this.form);">
</form>
  </body>
</html>

我试过的代码(这是所有功能)

public void xyz() {
        try {
            JSONObject json = new JSONObject();
            json.put("x", "Nishant");
            json.put("y",  34567);
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    10000);
            HttpConnectionParams.setSoTimeout(httpParams, 10000);
            HttpClient client = new DefaultHttpClient(httpParams);
            //
            //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
            //             "json={\"UserName\":1,\"FullName\":2}";
            String url = "url";

            HttpPost request = new HttpPost(url);
            request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                    "UTF8")));
            request.setHeader("json", json.toString());
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need

        } catch (Throwable t) {
            Toast.makeText(this, "Request failed: " + t.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }

    public void getServerData() throws JSONException, ClientProtocolException,
            IOException {

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
        HttpClient client = new DefaultHttpClient(httpParams);
        HttpPost request = new HttpPost(
                "url"); // add
                                                                                        // your
                                                                                        // url
                                                                                        // here...

        request.setHeader("Content-Type", "application/json");

        JSONObject json = new JSONObject();
        json.put("y", "55");
        json.put("x", "Nishant");
        Log.i("jason Object", json.toString());

        StringEntity se = new StringEntity(json.toString());

        se.setContentEncoding("UTF-8");
        se.setContentType("application/json");

        request.setEntity(se);

        HttpResponse response = client.execute(request);

        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        String _response = convertStreamToString(is);
        System.out.println("res--  " + _response);

        // Check if server response is valid code
        int res_code = response.getStatusLine().getStatusCode();
        System.out.println("code-- " + res_code);
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is),
                8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "url");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("", "Nishant"));
            nameValuePairs.add(new BasicNameValuePair("x:", "45"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

    protected void sendJson(final String email, final int pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); // For Preparing Message Pool for the child
                                    // Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(),
                        10000); // Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(
                            "url");
                    json.put("x", email);
                    json.put("y", pwd);
                    StringEntity se = new StringEntity(json.toString());
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                            "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /* Checking response */
                    if (response != null) {
                        InputStream in = response.getEntity().getContent(); // Get
                                                                            // the
                                                                            // data
                                                                            // in
                                                                            // the
                                                                            // entity
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    // createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); // Loop in the message queue
            }
        };

请告诉我为什么不发布?哪里可能做错了?

2 个答案:

答案 0 :(得分:1)

看起来像很多代码。我认为你可以更好地将JSON对象封装在一个单独的方法中,然后可能使用下面的例子,这对我来说非常有用。您似乎有很多我认为不必要的HTTP连接对象......

public static boolean sendJSONtoBLX(String path, JSONObject json)
        throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost(path);
    StringEntity se = new StringEntity(json.toString());
    httpost.setEntity(se);
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");
    @SuppressWarnings("rawtypes")
    ResponseHandler responseHandler = new BasicResponseHandler();
    @SuppressWarnings("unchecked")
    String response = httpclient.execute(httpost, responseHandler);
    JSONObject jsonResponse = new JSONObject(response);
    String serverResponse = jsonResponse.getString("success");

    if (serverResponse.equals("true")) {
        return true;
    } else {
        return false;
    }
}

我正在创建JSON对象:

public final static JSONObject writeJSON() throws Exception {
    JSONObject obj = new JSONObject();
    try {
        obj.put("x", "Nishant");
        obj.put("y",  34567);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

新信息:在本地测试后,看来这是Android无法访问https的SSL问题。与JSON等无关。上述答案适用于普通的http。

答案 1 :(得分:0)

只需将此代码放入您的代码中:

StringEntity oStringEntity = new StringEntity( json.toString());  
oStringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
request.setEntity(oStringEntity);

而不是:

request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());

如果这解决了你的问题,那么请接受它!