post代码

public static String httpPost(String url, String input) throws Exception {
        // 返回body
        String body = "";
        // 1、创建一个htt客户端
        HttpClient httpClient = new DefaultHttpClient();
        // 2、创建一个HttpPost请求
        HttpPost post = new HttpPost(url);

        post.addHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Accept", "application/json");
        // 设置参数
        StringEntity stringEntity = new StringEntity(input,Charset.forName("UTF-8"));
        post.setEntity(stringEntity);
        // 7、执行post请求操作,并拿到结果
        HttpResponse httpResponse = httpClient.execute(post);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, HTTP.UTF_8);
        }
        // EntityUtils.consume(entity);
        httpClient.getConnectionManager().shutdown();
        System.out.println(body.length());
        return body;
    }

你可能感兴趣的:(post代码)