简体   繁体   中英

JSON Post Request contains no parameters

I have a problem by my json post request. I created a JsonObject and want to post it to the server but the body of the post request which is received by the server contains nothing and I don't know why...

public class ServiceHandler {
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    String contentType = "application/json";
    public ServiceHandler() {
}

public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("name", "your name");
                jsonObj.put("message", "your message");

                StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
                httpPost.setEntity(entity);
            }

            httpResponse = httpClient.execute(httpPost);
        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }

            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }

        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return response;
}

Provide "Content-Type" header to request with value "application/json". It seems server can't found proper message body mapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM