【问题标题】:Problems with HTTP POST request for JSON object for content-type in AndroidAndroid中内容类型的JSON对象的HTTP POST请求问题
【发布时间】:2014-07-18 13:02:16
【问题描述】:

以下是我在运行 Android 4.1.2 的 Android 设备中的 HTTP POST 请求代码。我有问题:

  • 此代码在三星设备上完美运行,而在 HTC 设备上给出“内容类型不是应用程序/json”。

    public static String POST(String url, JSONObject obj) { Log.i("JSONPOSTBEGIN", "JSON POST 开始"); 输入流 inputStream = null; 字符串结果 = "";

    HttpClient httpclient = new DefaultHttpClient();
    
    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept", "application/json");
    
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
    
        HttpResponse httpResponse = mHhttpclient.execute(post);
    
        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
    
        // convert inputstream to string
        if(inputStream != null) {
            result = convertInputStreamToString(inputStream);
        } else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    Log.i("JSONPOSTEND", "End of JSON data post methos...");
    return result;
    

    }

【问题讨论】:

    标签: android json http


    【解决方案1】:

    要让它在 HTC 和所有设备上运行,您必须这样做

    private static HttpEntity getHttpEntity(String stringEntity) {
        HttpEntity entity = null;
        try {
            entity = new StringEntity(stringEntity, HTTP.UTF_8);
            ((StringEntity) entity).setContentType("application/json;charset=UTF-8");
            ((StringEntity) entity).setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    
        } catch (Exception e) {
            Log.d("error creating entity: " + stringEntity);
        }
        return entity;
    }
    

    【讨论】:

      【解决方案2】:

      请注意,标题可能是由此设置的

      新的 HttpPost(url);

      在你添加新的标题之前,比如“content-type”,你可能必须先调用 remove header (Content-type)....

      您需要记录才能解决所有问题。有关更多信息,请参阅接受的 ans here

      并在您的测试环境中登录 WIRE & HEADER

      【讨论】:

        猜你喜欢
        • 2015-02-18
        • 2015-09-07
        • 2012-11-30
        • 2023-03-28
        • 2018-03-22
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多