httpClient傳送get和post請求
阿新 • • 發佈:2021-07-18
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.8</version> </dependency>
【get請求】
package com.xt.postman; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import javax.swing.text.html.parser.Entity; import java.io.IOException; import java.io.InputStream; /** * @Author: TestRookie * @Date: 2021/7/18 15:26 * @Description: * */ public class TestGet { public static void main(String[] args) throws IOException { /** * 1.設定url * 2.設定請求方式,建立對應的請求方式物件 * 3.建立httpClient物件 * 4.傳送請求 * 5.獲取報文物件 * 6.報文物件格式化的輸出 */ String url = "http://test.lemonban.com/ningmengban/app/login/login.html"; HttpGet get = new HttpGet(url); CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent();//流物件 read /*byte[] bytes = new byte[1024]; while(content.read(bytes)!=-1){ System.out.println(new String(bytes)); }*/ String result = EntityUtils.toString(entity); System.out.println(result); } }
【post請求】
package com.xt.postman; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; 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.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * @Author: TestRookie * @Date: 2021/7/18 15:58 * @Description: * */ public class TestPost { public static void main(String[] args) throws IOException { /** * 1.設定url * 2.設定請求方式,建立對應的請求方式物件 * 3.建立httpClient物件 * 4.繫結引數 * 5.傳送請求 * 6.獲取報文物件 * 7.格式化報文 */ String url="http://test.lemonban.com/ningmengban/mvc/user/login.json"; HttpPost post = new HttpPost(url); //設定請求頭 注意引數要以form表單的形式提交 post.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); CloseableHttpClient client = HttpClients.createDefault(); //繫結引數 post.setEntity(new StringEntity("username=13311112222&password=4297f44b13955235245b2497399d7a93")); CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); System.out.println(result); } }
StringEntity stringEntity =new StringEntity(JSONObject.toJSONString(params),"UTF-8");