Java-HttpClient基本使用

HttpClient基本使用

1.HttpClient的maven依赖

	
		
			commons-httpclient
			commons-httpclient
			3.1
		

		
			org.apache.httpcomponents
			httpclient
			4.5.3
		
		
			org.apache.httpcomponents
			httpcore
			4.4.6
		
		
			org.apache.httpcomponents
			httpmime
			4.5.3
		
	

2.发送消息

public static String sendVipHome(String url, String requestJson) throws Exception{
    StringBuffer responseJson = new StringBuffer("");
    InputStream in = null;

    // 交互
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setContentCharset("UTF-8");  //设置编码格式 防止中文乱码
    httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    // 设置请求超时时间
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(10000);
    managerParams.setSoTimeout(2*60000);

    PostMethod post = new PostMethod(url);
    post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    post.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
    post.setRequestBody(requestJson);

    int status = httpClient.executeMethod(post);
    if (status != HttpStatus.SC_OK) {
        throw new IllegalStateException("Method failed: " + post.getStatusLine());
    }

    in = post.getResponseBodyAsStream();
    BufferedReader br=new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String line="";
    while((line=br.readLine())!=null){
       responseJson.append(line);
    }
    br.close();

    return responseJson.toString();
}

3.调用

	public static void main(String[] args) throws Exception {
    		String url = "http://127.0.0.1:8080/index";
    		User user = new User();
    		user.setUserCode("zhangsan");
    		user.setUserName("张三");
    		String requetJson = JSONObject.toJSONString(user);
    		System.out.println("客户端发送的参数:"+requetJson);
    		String result = sendVipHome(url, requetJson);
    		System.out.println("客户端接收到的结果:"+result);
    }

你可能感兴趣的:(HttpClient)