【问题标题】:httppost doesn't change the content typehttppost 不会改变内容类型
【发布时间】:2015-10-29 12:24:16
【问题描述】:

这是我的代码:

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(postUrl);
httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON);
StringEntity bodyEntity = new StringEntity("{\"name\":\"hello\"}");
bodyEntity.setContentType(MediaType.APPLICATION_JSON);
httpPost.setEntity(bodyEntity);

HttpResponse response = client.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);

我不断收到错误unsupported content type 虽然我的网络服务只需要json,但我检查了httpPost 内容类型,它始终是plain text,请问为什么它没有更改为JSON?

【问题讨论】:

    标签: java http-post


    【解决方案1】:

    试试这个代码

     public static void HttpPost() {
            try {
    
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(
                        "https://api.website.net/auth/token");
                StringEntity input = new StringEntity("{\"name\":\"hello\"}");
                post.setEntity(input);
                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
    

    【讨论】:

    • 这如何解决我的问题?内容类型在哪里?
    猜你喜欢
    • 2013-03-15
    • 2011-07-18
    • 2011-01-05
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 2014-07-31
    • 2013-05-29
    相关资源
    最近更新 更多