Java-Http


 1 import java.io.BufferedReader;
 2 import java.io.BufferedWriter;
 3 import java.io.IOException;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStreamWriter;
 6 import java.net.HttpURLConnection;
 7 import java.net.MalformedURLException;
 8 import java.net.URL;
 9 
10 /**
11  * HttpURLConnection
12  */
13 public class TestPost {
14     public static void main(String[] args) {
15         try {
16             URL url = new URL("");
17             HttpURLConnection connection =   (HttpURLConnection) url.openConnection();
18             connection.setRequestProperty("encoding", "UTF-8");
19             connection.setRequestMethod("POST");
20             connection.setDoInput(true);
21             connection.setDoOutput(true);
22             //根据连接对象创建输出流   将参数写入
23             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
24             bw.write("name=zhangsan&age=25");
25             bw.flush();
26             //创建输入流  获取响应数据
27             BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
28             String str;
29             StringBuffer sb = new StringBuffer();
30             while((str = br.readLine())!=null) {
31                 sb.append(str);
32             }
33             bw.close();
34             br.close();
35         } catch (MalformedURLException e) {
36             e.printStackTrace();
37         } catch (IOException e) {
38             e.printStackTrace();
39         }
40     }
41 }


1
import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.net.MalformedURLException; 5 import java.net.URL; 6 import java.net.URLConnection; 7 8 /** 9 * URLConnection
10  */
11 public class TestGet {
12     public static void main(String[] args) {
13         try {
14             URL url = new URL("https://www.baidu.com");
15             //打开连接
16             URLConnection openConnection = url.openConnection();
17             //获取连接中的输入流openConnection.getInputStream()返回字节流,通过转成字符流并包装一个缓冲流
18             BufferedReader br = new BufferedReader(
19                     new InputStreamReader(openConnection.getInputStream()));
20             String str;
21             StringBuffer sb = new StringBuffer();
22             while((str = br.readLine())!=null) {
23                 sb.append(str);
24             }
25             System.out.println(sb);
26             br.close();
27         } catch (MalformedURLException e) {
28             e.printStackTrace();
29         } catch (IOException e) {
30             e.printStackTrace();
31         }
32     }
33 }
 1 import java.io.IOException;
 2 import org.apache.http.HttpEntity;
 3 import org.apache.http.HttpResponse;
 4 import org.apache.http.client.ClientProtocolException;
 5 import org.apache.http.client.HttpClient;
 6 import org.apache.http.client.methods.HttpGet;
 7 import org.apache.http.impl.client.HttpClients;
 8 import org.apache.http.util.EntityUtils;
 9 
10 /**
11  * HttpGet
12  */
13 public class HttpClientGetTest {
14     public static void main(String[] args) {
15         HttpClient client = HttpClients.createDefault();
16         try {
17             HttpGet get = new HttpGet("http://www.baidu.com");
18             HttpResponse response = client.execute(get);
19             HttpEntity entity = response.getEntity();
20             String result = EntityUtils.toString(entity,"UTF-8");
21             
22             System.out.println(result);
23         } catch (ClientProtocolException e) {
24             e.printStackTrace();
25         } catch (IOException e) {
26             e.printStackTrace();
27         }
28     }
29 }
 1 import java.io.IOException;
 2 import java.util.ArrayList;
 3 import java.util.List;
 4 
 5 import org.apache.http.HttpEntity;
 6 import org.apache.http.HttpResponse;
 7 import org.apache.http.client.ClientProtocolException;
 8 import org.apache.http.client.HttpClient;
 9 import org.apache.http.client.entity.UrlEncodedFormEntity;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.message.BasicNameValuePair;
13 import org.apache.http.util.EntityUtils;
14 
15 /**
16  * HttpPost
17  */
18 public class HttpClientPostTest {
19     public static void main(String[] args) {
20         try {
21             HttpClient client = HttpClients.createDefault();
22             HttpPost post = new HttpPost("http://www.baidu.com");
23             //参数集合
24             List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
25             //添加数据
26             parameters.add(new BasicNameValuePair("name", "zhangsan"));
27             //将参数放到实体中
28             post.setEntity(new UrlEncodedFormEntity(parameters));
29             //设置请求方式
30             HttpResponse response = client.execute(post);
31             HttpEntity entity = response.getEntity();
32             String result = EntityUtils.toString(entity,"UTF-8");
33             //打印响应信息
34             System.out.println(result);
35         } catch (ClientProtocolException e) {
36             e.printStackTrace();
37         } catch (IOException e) {
38             e.printStackTrace();
39         }
40     }
41 }

 

1         <!-- httpclient -->
2         <dependency>
3             <groupId>org.apache.httpcomponents</groupId>
4             <artifactId>httpclient</artifactId>
5             <version>4.5.5</version>
6         </dependency>

 

  1 import java.io.IOException;
  2 
  3 import org.apache.http.HttpEntity;
  4 import org.apache.http.HttpStatus;
  5 import org.apache.http.client.CookieStore;
  6 import org.apache.http.client.config.RequestConfig;
  7 import org.apache.http.client.methods.CloseableHttpResponse;
  8 import org.apache.http.client.methods.HttpGet;
  9 import org.apache.http.client.methods.HttpPost;
 10 import org.apache.http.client.methods.HttpRequestBase;
 11 import org.apache.http.entity.StringEntity;
 12 import org.apache.http.impl.client.BasicCookieStore;
 13 import org.apache.http.impl.client.CloseableHttpClient;
 14 import org.apache.http.impl.client.HttpClients;
 15 import org.apache.http.util.EntityUtils;
 16 /**
 17  * @ClassName: HttpReqUtil
 18  * @Description: http请求工具类
 19  */
 20 public class HttpReqUtil {
 21 
 22     private static CookieStore cookieStore = new BasicCookieStore();
 23     /**
 24      * @Title: httpReqConfig
 25      * @Description: 请求配置
 26      * @param httpRequestBase
 27      * @return void  返回类型
 28      * @throws
 29      */
 30     public static void httpReqConfig(HttpRequestBase httpRequestBase) {
 31         // header配置
 32         httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
 33         httpRequestBase.setHeader("Accept", "*/*");
 34         httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
 35         httpRequestBase.setHeader("Accept-Encoding", "gzip, deflate");
 36 
 37         // 请求超时设置
 38         RequestConfig config = RequestConfig.custom() //获取Builder对象
 39                 .setConnectionRequestTimeout(20000)  //设置请求超时时间
 40                 .build();  //构建RequestConfig对象
 41 
 42         httpRequestBase.setConfig(config);  //将RequestConfig添加到请求中
 43     }
 44 
 45     /**
 46      * @Title: sendGet
 47      * @Description: 发送get请求
 48      * @param url
 49      * @param param
 50      * @return String  返回类型
 51      * @throws
 52      */
 53     public static String sendGet(String url, String param) {
 54 
 55         // 初始化
 56         String result = null;
 57         CloseableHttpResponse response = null;
 58         String finalUrl = url + "?" + param;
 59         // 创建httpclient
 60         CloseableHttpClient httpclient = HttpClients.custom()
 61         //请求中cookie由cookie管理,存储第一次登陆后服务器返回的cookie,之后登陆后的请求都带上该cookie
 62                 .setDefaultCookieStore(cookieStore)
 63                 .build();
 64         
 65         try {
 66             // 发送get请求+header
 67             HttpGet httpGet = new HttpGet(finalUrl);
 68 
 69             // 添加header
 70             httpReqConfig(httpGet);
 71             response = httpclient.execute(httpGet);
 72 
 73             // 获取响应内容
 74             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
 75                 HttpEntity entity = response.getEntity();
 76                 result = EntityUtils.toString(entity);
 77             }
 78         } catch (Exception e) {
 79             e.printStackTrace();
 80         } finally {
 81             try {
 82                 // 关闭数据流
 83                 if(response!=null) {
 84                     response.close();
 85                 }
 86             } catch (IOException e) {
 87                 e.printStackTrace();
 88             }
 89             try {
 90                 // 关闭连接
 91                 if(httpclient!=null) {
 92                     httpclient.close();
 93                 }
 94             } catch (IOException e) {
 95                 e.printStackTrace();
 96             }
 97         }
 98         return result;
 99     }
100 
101     /**
102      * @Title: sendPost
103      * @Description: 发送post请求
104      * @param url
105      * @param param
106      * @return String  返回类型
107      * @throws
108      */
109     public static String sendPost(String url, String param) {
110         // 初始化
111         String result = null;
112         CloseableHttpResponse response = null;
113         // 创建httpclient
114         CloseableHttpClient httpclient = HttpClients.custom()
115                 .setDefaultCookieStore(cookieStore)
116                 .build();
117             try {
118                 HttpPost httpPost = new HttpPost(url);
119                 // 添加header
120                 httpReqConfig(httpPost);
121 
122                 StringEntity stringEntity = new StringEntity(param, "UTF-8");
123                 stringEntity.setContentType("application/x-www-form-urlencoded");
124 
125                 // 发送post请求
126                 httpPost.setEntity(stringEntity);
127                 response = httpclient.execute(httpPost);
128 
129                 // 获取响应内容
130                 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
131                     HttpEntity entity = response.getEntity();
132                     result = EntityUtils.toString(entity);
133                 }
134             } catch (Exception e) {
135                 e.printStackTrace();
136             } finally {
137                 try {
138                     // 关闭数据流
139                     if(response!=null) {
140                         response.close();
141                     }
142                 } catch (IOException e) {
143                     e.printStackTrace();
144                 }
145                 try {
146                     // 关闭连接
147                     if(httpclient!=null) {
148                         httpclient.close();
149                     }
150                 } catch (IOException e) {
151                     e.printStackTrace();
152                 }
153             }
154         return result;
155     }
156 
157     public static void main(String[] args) {
158 
159         // 案例:登陆接口
160         String url_a = "http://www.nuandao.com/public/lazyentrance";
161         String param_a = "isajax=1&remember=1&email=xxxxx@qq.com&password=testing1?&agreeterms=1&itype=&book=1&m=0.2757277030262314";
162         sendPost(url_a, param_a);
163 
164 //        // 案例:购物车接口
165 //        String url_b = "http://www.nuandao.com/shopping/cart";
166 //        String param_b = "countdown=1&m=0.3810762454661424";
167 //        sendPost(url_b, param_b);
168 
169         /*
170          * //案例 String url_c = "http://www.nuandao.com/Ajax/personal"; String
171          * param_c =
172          * "default=1&pagesign=user&url=http%3A%2F%2Fwww.nuandao.com%2Fuser%2Fmyorder&m=0.7948146575033792";
173          * sendPost(url_c,param_c);
174          * 
175          * //案例 String url_d =
176          * "https://m.jiuxian.com/m_v1/goods/get_goods_num_by_province"; String
177          * param_d = "goods_id=28045&province_id=500"; sendPost(url_d,param_d);
178          */
179     }
180 }

 

posted @ 2018-10-08 18:23  为你编程  阅读(1066)  评论(0编辑  收藏  举报