PostMethod和HttpPost的区别

老版:PostMethod

  1. public class HttpTests {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      * @throws Exception 
  6.      */  
  7.     public static void main(String[] args) throws Exception {  
  8.         HttpClient httpclient = new HttpClient();  
  9.         PostMethod httpPost =new PostMethod("******/abc");  
  10.         NameValuePair[] param = { new NameValuePair("username""vip")};  
  11.         httpPost.setRequestBody(param);   
  12.         httpclient.executeMethod(httpPost);  
  13.     }  
  14.   

新版:HttpPost

	public static String getMes(String url, String params) {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost htPost = new HttpPost(url);
		String backMes = null;
		try {
			htPost.setHeader("content-type", "application/json");
			StringEntity reqEntity = new StringEntity(params);
			htPost.setEntity(reqEntity);
			HttpResponse httpResponse = client.execute(htPost);
			HttpEntity entity = httpResponse.getEntity();
			backMes = EntityUtils.toString(entity, "UTF-8").toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				client.close();
				client = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return backMes;
	}


你可能感兴趣的:(PostMethod和HttpPost的区别)