此部落格為:fiddler 抓包 java httpclient 發起post請求
從其他部落格看到的方法:
1. jvm 設定啟動代理參數
-DproxySet=true
-DproxyHost=127.0.0.1
-DproxyPort=8888
失敗!
2.代碼中設定代理
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8888");
失敗!
解決問題:
1. 發起的 請求體 用 StringEntity 類建立,并且加入utf-8字元集,否則中文在抓包資料中亂碼
String body = "{\"config\":{\"wo張三\":\"123\",\"mac\":\"FC:2F:EF:72:5F:43\"}}";
StringEntity entity = new StringEntity(body,"utf-8");
2. fiddler 抓包java發起的請求。需要先開啟fiddler,設定代理端口為 8888,或者其他
代理設定的正确姿勢:
3.代碼中添加代理 使用HttpHost建立代理,
HttpHost proxy = new HttpHost("127.0.0.1",8888)
response = client.execute(proxy,httpPost);
這個問題花了1天時間,以此紀念
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.StatusLine;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class test{
public void testpost() throws IOException{
//普通的client 設定方法
CloseableHttpClient client = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
String url = "http://192.168.10.16/api/ilink/device/gwpolicy_authpolicy_add?;
//傳送json類型的字元串的請求體
String body = "{\"config\":{\"wo張三\":\"123\",\"mac\":\"FC:2F:EF:72:5F:43\"}}";
//建構請求實體,utf-8字元集
StringEntity entity = new StringEntity(body,"utf-8");
HttpPost httpPost = new HttpPost(url) ;
//添加請求頭
httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
//添加實體到post請求中
httpPost.setEntity(entity);
//fiddler 抓包 開啟的代理,若不需要,則注釋,client.execute()的參數就不傳入此代理
HttpHost proxy = new HttpHost("127.0.0.1",8888);
//發起請求
response = client.execute(proxy,httpPost);
//擷取響應狀态碼
StatusLine statusLine = response.getStatusLine();
int statu = statusLine.getStatusCode();
System.out.println(statu);
//擷取響應實體
HttpEntity rentity = response.getEntity();
//響應實體解碼
entityStr = EntityUtils.toString(rentity, "UTF-8");
System.out.println(entityStr);
}
}