java模擬http請求


java模擬http發送請求,第一種是HttpURLConnection發送post請求,第二種是使用httpclient模擬post請求,

方法一:

 1 package main.utils;
 2 
 3 import java.io.*;
 4 import java.net.HttpURLConnection;
 5 import java.net.URL;
 6 
 7 public class HttpUtilTest {
 8     Log log = new Log(this.getClass());//初始化日志類
 9     /**
10      * @作用 使用urlconnection
11      * @param url
12      * @param Params
13      * @return
14      * @throws IOException
15      */
16     public String sendPost(String url,String Params)throws IOException{
17         OutputStreamWriter out = null;
18         BufferedReader reader = null;
19         String response="";
20         try {
21             URL httpUrl = null; //HTTP URL類 用這個類來創建連接
22             //創建URL
23             httpUrl = new URL(url);
24             //建立連接
25             HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
26             conn.setRequestMethod("POST");
27             conn.setRequestProperty("Content-Type", "application/json");
28             conn.setRequestProperty("connection", "keep-alive");
29             conn.setUseCaches(false);//設置不要緩存
30             conn.setInstanceFollowRedirects(true);
31             conn.setDoOutput(true);
32             conn.setDoInput(true);
33             conn.connect();
34             //POST請求
35             out = new OutputStreamWriter(
36                     conn.getOutputStream());
37             out.write(Params);
38             out.flush();
39             //讀取響應
40             reader = new BufferedReader(new InputStreamReader(
41                     conn.getInputStream()));
42             String lines;
43             while ((lines = reader.readLine()) != null) {
44                 lines = new String(lines.getBytes(), "utf-8");
45                 response+=lines;
46             }
47             reader.close();
48             // 斷開連接
49             conn.disconnect();
50 
51             log.info(response.toString());
52         } catch (Exception e) {
53         System.out.println("發送 POST 請求出現異常!"+e);
54         e.printStackTrace();
55         }
56         //使用finally塊來關閉輸出流、輸入流
57         finally{
58         try{
59             if(out!=null){
60                 out.close();
61             }
62             if(reader!=null){
63                 reader.close();
64             }
65         }
66         catch(IOException ex){
67             ex.printStackTrace();
68         }
69     }
70 
71         return response;
72     }
73 }

 

 方法二:使用httpclient實現

 1 import java.io.UnsupportedEncodingException;
 2 import java.net.URLEncoder;
 3 
 4 import main.utils.Log;
 5 
 6 import org.apache.http.client.methods.CloseableHttpResponse;
 7 import org.apache.http.client.methods.HttpPost;
 8 import org.apache.http.entity.ContentType;
 9 import org.apache.http.entity.StringEntity;
10 import org.apache.http.impl.client.CloseableHttpClient;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.util.EntityUtils;
13 
14 //post請求方法
15 public  String sendPost(String url, String data) {
16    String response = null;
17    log.info("url: " + url);
18    log.info("request: " + data);
19    try {
20        CloseableHttpClient httpclient = null;
21        CloseableHttpResponse httpresponse = null;
22        try {
23            httpclient = HttpClients.createDefault();
24            HttpPost httppost = new HttpPost(url);
25            StringEntity stringentity = new StringEntity(data,
26                    ContentType.create("text/json", "UTF-8"));
27            httppost.setEntity(stringentity);
28            httpresponse = httpclient.execute(httppost);
29            response = EntityUtils
30                    .toString(httpresponse.getEntity());
31            log.info("response: " + response);
32        } finally {
33            if (httpclient != null) {
34                httpclient.close();
35            }
36            if (httpresponse != null) {
37                httpresponse.close();
38            }
39        }
40    } catch (Exception e) {
41        e.printStackTrace();
42    }
43    return response;
44 }

 

 

附:httpClient 4.3中文手冊,來自開源中國:https://my.oschina.net/u/565871/blog/701214

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM