1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > httpclient发送Get请求和Post请求

httpclient发送Get请求和Post请求

时间:2019-08-18 15:48:20

相关推荐

httpclient发送Get请求和Post请求

创建HttpClient发送请求、接收响应

Get请求简介get无参数get有参数 Post请求简介post携带JSON参数post携带表单参数 postman自动生成OKhttp代码

Get请求简介

1). 创建HttpClient对象,可以使用HttpClients.createDefault();2). 如果是无参数的GET请求,则直接使用构造方法HttpGet(String url)创建HttpGet对象即可;3)如果是带参数GET请求,则可以先使用URIBuilder(String url)创建对象,再调用addParameter(Stringparam, String value)`, 或setParameter(String param, String)

value)来设置请求参数,并调用build()方法构建一个URI对象。4). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest

request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String

name)等方法可获取服务器的响应头;5)调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。6). 释放连接。

构建一个Maven项目,引入如下依赖

<!-- /artifact/org.apache.httpcomponents/httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.8</version></dependency>

get无参数

如果是无参数的GET请求,则直接使用构造方法HttpGet(String url)创建HttpGet对象即可

/***普通的GET请求*/public class DoGET {public static void main(String[] args) throws Exception {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http GET请求HttpGet httpGet = new HttpGet("");CloseableHttpResponse response = null;try {// 执行请求response = httpclient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {//请求体内容String content = EntityUtils.toString(response.getEntity(), "UTF-8");//内容写入文件FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");System.out.println("内容长度:"+content.length());}} finally {if (response != null) {response.close();}//相当于关闭浏览器httpclient.close();}}}

get有参数

如果是带参数GET请求,则可以先使用URIBuilder(String url)创建对象,再调用addParameter(Stringparam, String value)

public class HttpclientTest {@Testpublic void httpGet() throws IOException {// 1.创建httpclientCloseableHttpClient httpClient = HttpClients.createDefault();//2. 创建HttpGet,设置URL访问地址String urlTest = "https://XXXX/XXX/shopping/platformInfo?platformid=7";HttpGet httpGet = new HttpGet(urlTest);// 3. 请求执行,获取响应CloseableHttpResponse response = httpClient.execute(httpGet);//解析响应if (response.getStatusLine().getStatusCode() == 2000) {String content = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println(content.length());}// 4.获取响应实体HttpEntity entity = response.getEntity();System.out.println(EntityUtils.toString(entity, "utf-8"));response.close();httpClient.close();}

代码中使用的是公司接口,请求URL前缀就XXX表示了,get请求如图所示

运行结果:我们已经看到get接口成功返回一条数据

Post请求简介

1). 创建HttpClient对象,可以使用HttpClients.createDefault();2). 如果是无参数的POST请求,则直接使用构造方法HttpPost(String url)创建HttpPost对象即可;3)如果是带参数POST请求,先构建HttpEntity对象并设置请求参数,然后调用setEntity(HttpEntityentity)创建HttpPost对象。4). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest

request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String

name)等方法可获取服务器的响应头;5)调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。6). 释放连接。

post携带JSON参数

如果是带JSON参数POST请求,先构建HttpEntity对象并设置请求参数,因为我们的参数是JSON格式的,需要将请求对象转换成string类型的,然后调用setEntity(HttpEntityentity)创建HttpPost对象

首先我们先创建一个请求实体类PostData,代码如图所示

/*** @param* @author wcy* @create /10/15* @return* @description**/public class PostData {private String categoryid;private int currentPage;private String end_time;private int pageSize;private int platformid;private String start_time;private int step_id;public String getCategoryid() {return categoryid;}public void setCategoryid(String categoryid) {this.categoryid = categoryid;}public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public String getEnd_time() {return end_time;}public void setEnd_time(String end_time) {this.end_time = end_time;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) {this.pageSize = pageSize;}public int getPlatformid() {return platformid;}public void setPlatformid(int platformid) {this.platformid = platformid;}public String getStart_time() {return start_time;}public void setStart_time(String start_time) {this.start_time = start_time;}public int getStep_id() {return step_id;}public void setStep_id(int step_id) {this.step_id = step_id;}}

@Testpublic void httpPost() throws IOException {// 1.创建httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();// 2.创建post对象,设置URL访问地址String url = "https://XxX/XxX/shopping/goodsRank";HttpPost httpPost = new HttpPost(url);CloseableHttpResponse response = null;try {PostData data = new PostData();data.setCategoryid("");data.setCurrentPage(1);data.setEnd_time("-11-02");data.setPageSize(20);data.setPlatformid(1);data.setStart_time("-11-02");data.setStep_id(464);String bodyEntity = JSON.toJSONString(data);HttpEntity entity = new StringEntity(bodyEntity, ContentType.APPLICATION_JSON);httpPost.setEntity(entity);//发送post请求response = httpClient.execute(httpPost);//解析响应if (response.getStatusLine().getStatusCode() == 200) {//获取响应数据entity = response.getEntity();System.out.println(EntityUtils.toString(entity, "utf-8"));}}catch (IOException e){e.printStackTrace();}}

运行结果:

post携带表单参数

post请求传递参数的形式是将参数放入表单请求体中,然后将表单对象放入请求体中传递。

//1.获得一个httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();//2.生成一个post请求HttpPost httpPost = new HttpPost("/");//3.请求参数添加到请求体中,表单提交List<NameValuePair> nvpList = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair(key, val));UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, charset);httpPost.setEntity(formEntity);//4.执行get请求并返回结果CloseableHttpResponse response = httpclient.execute(httpPost);try {//5.处理结果响应体HttpEntity entity = response.getEntity();} finally {response.close();}

postman自动生成OKhttp代码

首先在postman编写好post请求的URL,请求参数,请求方式,请求头

点击sends按钮右侧的code弹窗展示,如图所示

框里面的代码就是自动生成的,我们可以复制代码到idea中,需要在maven`装下OKhhtp的依赖

官网连接:/

OkHttpClient client = new OkHttpClient().newBuilder().build();MediaType mediaType = MediaType.parse("text/plain");RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("categoryid","").addFormDataPart("currentPage","1").addFormDataPart("end_time ","-11-01").addFormDataPart("pageSize","20").addFormDataPart("platformid ","1").addFormDataPart("start_time ","-11-01").addFormDataPart("step_id ","464").build();Request request = new Request.Builder().url("https://XXX/XXX/shopping/goodsRank").method("POST", body).addHeader("Cookie", "laravel_session=eyJpdiI6IkRxcWx6M201UHRWMWFWeDY3b0RURmc9PSIsInZhbHVlIjoid0pSM241cmgvRUk5WndHTnc2azlzNFpHVDh6MCt5R1pSV21pQXRPRDB1eEpyMThNZVUrelRKYzJHSVUzNHp3T290RHppOVNvSFZ3Z2VCQ2g4SEFQUjBXSGpRL3VkcUJiRUFzRGc5b21BRnhOUUwzUkNENlhzUEJlVGtWZkhZNGoiLCJtYWMiOiIyYzM1NDhkYzQ0YmZiNjQ5OWIwZjg1NDA3NTYxZTcyM2IyODAxNWI1ZGU4NmEzOTE2YjRmOTBjYzQzMzUyNjY1In0%3D").build();Response response = client.newCall(request).execute();System.out.println(response);}

OKhttp的语法跟httpclient差不多,都是http工具类

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。