【问题标题】:JSON Post Request contains no parametersJSON Post 请求不包含任何参数
【发布时间】:2016-04-24 05:16:30
【问题描述】:

我的 json 发布请求有问题。我创建了一个 JsonObject 并想将其发布到服务器,但是服务器接收到的发布请求的正文中什么都不包含,我不知道为什么......

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

【问题讨论】:

    标签: java android html json android-studio


    【解决方案1】:

    为请求提供“Content-Type”标头,其值为“application/json”。似乎服务器找不到正确的消息正文映射器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2017-04-07
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 2011-04-30
      • 2016-06-04
      相关资源
      最近更新 更多