HttpClient示例

戚薇 Java经验 发布时间:2023-05-21 21:11:38 阅读数:13931 1
下文笔者讲述HttpClient发送post、get请求的方法分享,如下所示

httpClient post请求

/**
 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
 */
public void post() {
	// 创建默认的httpClient实例.
	CloseableHttpClient httpclient = HttpClients.createDefault();
	// 创建httppost
	HttpPost httppost = new HttpPost("http://localhost:8080/test");
	// 创建参数队列
	list<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("type", "house"));
	UrlEncodedFormEntity uefEntity;
	try {
		 uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		 httppost.setEntity(uefEntity);
		 System.out.println("executing request " + httppost.getURI());
		CloseableHttpResponse response = httpclient.execute(httppost);
		try {
		   HttpEntity entity = response.getEntity();
			if (entity != null) {
		 	 System.out.println("--------------------------------------");
		 	 System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
			 System.out.println("--------------------------------------");
			}
		} 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();
			}
	}
}

httpClient发送get请求

/**
 * 发送 get请求
 */
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//创建httpget
HttpGet httpget = new HttpGet("http://www.java265.com/");
System.out.println("executing request " + httpget.getURI());
//执行get请求
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
//输出响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
  //输出响应内容长度
 System.out.println("Response content length: " + entity.getContentLength());
  //输出响应内容
  System.out.println("Response content: " + EntityUtils.toString(entity)); 
 } 
  System.out.println("------------------------------------");
  } finally {
  response.close();
  }
} catch (ClientProtocolException e) {
  e.printStackTrace(); 
} catch (ParseException e) {
 e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} finally {
// 关闭连接,释放资源
 try {
  httpclient.close();
 }catch (IOException e) {
  e.printStackTrace();
 }
 }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202305/16846747246565.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者