0

JSONデータをHTTPリクエストURLに投稿するために約5つの方法を使用しましたが、実りがありません。希望どおりにフォーマットされたJSONを投稿していません。送信したいJSONの次のとおりで、現在、 HTML:

必要な JSON は次のとおりです: {"x":"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>

私が試したコード(ITはすべての機能です)

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
            }
        };

投稿しない理由を教えてください。どこで間違っている可能性がありますか?

4

2 に答える 2

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に対しては正常に機能します。

于 2013-07-31T11:36:09.087 に答える
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());

これで問題が解決した場合は、それを受け入れてください!

于 2013-07-31T11:34:22.827 に答える