http post 请求示例

public static String post6(String URL,String json) {
String obj=null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
httppost.addHeader(“Content-type”, “application/json; charset=utf-8”);
httppost.setHeader(“Accept”, “application/json”);
try {
StringEntity s = new StringEntity(json,Charset.forName(“UTF-8”)); //对参数进行编码,防止中文乱码
s.setContentEncoding(“UTF-8”);
httppost.setEntity(s);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
//获取相应实体
if (response.getEntity() != null) {
obj=EntityUtils.toString(response.getEntity(), “UTF-8”);
}

        } finally {  
            response.close();  
        }  
    } catch (ClientProtocolException e) {  
        e.printStackTrace();  
    } catch (UnsupportedEncodingException e1) {  
        e1.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        // 关闭连接,释放资源    
        try {  
            httpclient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    return obj;
} 

猜你喜欢

转载自blog.csdn.net/steven27_3/article/details/100661892
今日推荐