标签:imp trace 方法 code sys pcl java util prot
在java后台开发中,我们有时候需要调用其他网站的接口进行数据的获取操作,我们一般会采用
1.java net 包中的URL 类,进行网络的数据获取
2.使用apache提供的HttpClient进行网络中数据的获取;
这里我们使用第二种方式,使用apache 提供的HttpClient进行数据的获取,接口的对接,下面附上HttpClientUtil 工具类,实现了POST与GET方法
package com.project.util; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientUtil { //使用HttpClient 进行doGET请求 public static String doGet(String url) { String result =null; //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法 CloseableHttpClient httpclient =HttpClients.createDefault(); HttpGet httpget =new HttpGet(url); try { HttpResponse response=httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if(entity !=null) { result =EntityUtils.toString(entity,"UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(httpclient !=null) { httpclient.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public static void main(String[] args) { String str=doGet("http://www.baidu.com"); System.out.println(str); } //使用HttpClient 进行dopOSTT请求,适合发送的数据为json数据格式 public static String doPOST(String url,String outstr) { //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法 CloseableHttpClient httpclient =HttpClients.createDefault(); HttpPost httppost =new HttpPost(url); String result =null; try { httppost.setEntity(new StringEntity(outstr, "UTF-8")); HttpResponse response=httpclient.execute(httppost); HttpEntity entity=response.getEntity(); if(entity !=null) { result =EntityUtils.toString(entity,"UTF-8"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(httpclient !=null) { httpclient.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } }
HttpClient--使用HttpClient进行Get Post请求访问
标签:imp trace 方法 code sys pcl java util prot
原文地址:https://www.cnblogs.com/iscys/p/9502601.html