使用Apache的HttpClient可以从客户端发送HTTP请求到服务器端以一种很简单的方式
pom依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency>
Post请求
public static JSONObject httpPost(String url) throws IOException{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("name","pzw")); params.add(new BasicNameValuePair("email","pzw@163.com")); HttpEntity httpEntity = new UrlEncodedFormEntity(params); post.setEntity(httpEntity); CloseableHttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); String html = EntityUtils.toString(entity); return JSONObject.parseObject(html); }
大致步骤
1.创建客户端
2.声明请求类型,将URL作为参数传入
3.使用NameValuePair对象传递参数
4.创建HttpEntity,并将请求的信息放入httpEntity比如参数,请求方式
5.发起请求
6.使用HttpEntity将请求的返回的值转为Json的形式