我尝试将JSON对象发送到服务器时失败

时间:2014-07-10 15:38:50

标签: java android

我有一个JsonObject,我想从我的Android客户端发送到服务器。

我正在关注一些教程和代码,但服务器总是收到一个空的帖子请求。

这是我的代码:

public String POST(String url, JSONObject object) {

    InputStream inputStream = null;
    String result = "";

    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 4. convert JSONObject to JSON to String
        json = object.toString();

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the
        // content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

        Log.i("telo","respuesta: "+result);

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

private String convertInputStreamToString(InputStream inputStream)
        throws IOException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

我做错了什么?一些帮助

感谢

3 个答案:

答案 0 :(得分:0)

试试这个例子:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("object", object.toString()));

httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    InputStream instream = entity.getContent();
    try {
        // do something useful with instream
    } finally {
        instream.close();
    }
}

答案 1 :(得分:0)

尝试改变:(“Content-type”,“application / json”); to(“Content-Type”,“application / json”);

答案 2 :(得分:-1)

我认为你应该使用.toJSONString()而不是.toString()

请尝试:)