已知两种方法。一种是通过httpclient实现(貌似很简单,以后看一下),一种是以下方法:

Client实现:

package common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map; /**
* Created by zipon on 2018/8/27.
*/
public class HttpClientUtil {
Logger log = new LogUtil("http_log").logger;
/**
* Post方式 得到JSONObject
*
* @param params post参数
* @param url
* @encoding 编码格式,这里直接写死为utf-8
* @return
*/
public JSONObject doPost(JSONObject params, String url) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null; JSONObject resultJsonObject = new JSONObject();
try {
StringEntity entity = new StringEntity(params.toString(),"utf-8");
HttpPost httpPost = new HttpPost(url);
//httpPost.addHeader("Content-Type","application/json");
// 为HttpPost设置实体数据
httpPost.setEntity(entity);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
log.info("请求headers信息:");
String headerList ="";
for (Header header :httpPost.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info(headerList);
log.info("请求body:");
log.info(httpEntityToJSONObject(httpPost.getEntity()));
// HttpClient 发送Post请求
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// CloseableHttpResponse
HttpEntity httpEntity = httpResponse.getEntity();
resultJsonObject = httpEntityToJSONObject(httpEntity);
}else{
resultJsonObject.put("errorMessage",httpResponse);
}
log.info("返回headers信息:");
log.info(httpResponse.getAllHeaders());
log.info("返回body:");
log.info(httpResponse.getEntity());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally {
httpResponse.close();
httpClient.close();
}
return resultJsonObject;
} /**
* 没有headers 没有cookie插入的快速post
* @param params
* @param url
* @return
* @throws IOException
*/
// public BaseResponse doPost(JSONObject params, String url) throws IOException {
// //创建httpClient连接
// CloseableHttpClient httpClient = HttpClients.createDefault();
// CloseableHttpResponse httpResponse = null;
//
// BaseResponse baseResponse = new BaseResponse();
// try {
// StringEntity entity = new StringEntity(params.toString(),"utf-8");
// HttpPost httpPost = new HttpPost(url);
// // 为HttpPost设置实体数据
// httpPost.setEntity(entity);
//// 默认Content-Type
// httpPost.addHeader("Content-Type","application/json");
// System.out.println(httpEntityToJSONObject(httpPost.getEntity()));
// // HttpClient 发送Post请求
// httpResponse = httpClient.execute(httpPost);
// baseResponse = httpResponseToBaseResponse(httpResponse);
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// httpResponse.close();
// httpClient.close();
// }
// return baseResponse;
// } /**
* 主用这个
* @param params
* @param url
* @param headers
* @param cookie
* @return
* @throws IOException
*/
public BaseResponse doPost(JSONObject params, String url ,JSONObject headers ,String cookie) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null; BaseResponse baseResponse = new BaseResponse();
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity;
if (headers.get("Content-Type")=="application/x-www-form-urlencoded") {
List<NameValuePair> pairs = new ArrayList<>(32);
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key,params.get(key).toString()));
}
log.info(pairs);
entity = new UrlEncodedFormEntity(pairs,"utf-8");
}
else {
entity = new StringEntity(params.toString(), "utf-8");
}
addHeaders(httpPost,headers);
addCookies(httpPost,cookie);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
String headerList ="";
for (Header header :httpPost.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
// httpPost.addHeader("Content-Type","application/json");
// 为HttpPost设置实体数据
httpPost.setEntity(entity);
log.info("请求body:\n"+httpEntityToJSONObject(httpPost.getEntity()));
// log.info(httpEntityToJSONObject(httpPost.getEntity()));
// HttpClient 发送Post请求
httpResponse = httpClient.execute(httpPost);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:\n"+baseResponse.getResponseBody());
// log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************"); } catch (Exception e) {
e.printStackTrace();
}finally {
httpResponse.close();
httpClient.close();
}
return baseResponse;
} //
// public JSONObject getJSONObjectByGet(String url) throws IOException {
// JSONObject resultJsonObject=null;
//
// //创建httpClient连接
// CloseableHttpClient httpClient = HttpClients.createDefault();
// // HttpClient 发送Post请求
// CloseableHttpResponse httpResponse = null;
// try{
// StringBuilder urlStringBuilder=new StringBuilder(url);
// //利用URL生成一个HttpGet请求
// HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
//// httpGet.setHeader("Content-Type","text/123");
// System.out.println(httpGet.getMethod());
// for (Header header :httpGet.getAllHeaders()){
// String key = header.getName();
// String value = header.getValue();
// System.out.println(String.format("%s:%s",key,value));
// }
// System.out.println(httpGet.getProtocolVersion());
// System.out.println(httpGet.getRequestLine());
//
// httpResponse=httpClient.execute(httpGet);
// } catch (Exception e) {
// e.printStackTrace();
// }finally{
// httpResponse.close();
// httpClient.close();
// }
// //得到httpResponse的状态响应码
// if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
// //得到httpResponse的实体数据
// HttpEntity httpEntity=httpResponse.getEntity();
// resultJsonObject = httpEntityToJSONObject(httpEntity);
// }
// return resultJsonObject;
// } /**
* 不带headers、cookies参数的get请求
* @param url
* @return
* @throws IOException
*/
public BaseResponse doGet(String url) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpClient 发送get请求
CloseableHttpResponse httpResponse = null;
BaseResponse baseResponse = new BaseResponse();
try{
StringBuilder urlStringBuilder=new StringBuilder(url);
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
String headerList ="";
for (Header header :httpGet.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
httpResponse=httpClient.execute(httpGet);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:");
log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally{
httpResponse.close();
httpClient.close();
}
return baseResponse;
} public BaseResponse doGet(String url,JSONObject headers,String cookies) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpClient 发送get请求
CloseableHttpResponse httpResponse = null;
BaseResponse baseResponse = new BaseResponse();
try{
StringBuilder urlStringBuilder=new StringBuilder(url);
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
addHeaders(httpGet,headers);
addCookies(httpGet,cookies);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
String headerList ="";
for (Header header :httpGet.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
httpResponse=httpClient.execute(httpGet);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:");
log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally{
httpResponse.close();
httpClient.close();
}
return baseResponse;
} /**
* 将HttpEntity类转换为JSONObject封装方法,表单键值对格式直接put到formData里去
* @param httpEntity
* @return
*/
public JSONObject httpEntityToJSONObject(HttpEntity httpEntity){
StringBuilder entityStringBuilder=new StringBuilder();
JSONObject resultJsonObject=new JSONObject();
String jsonStr=null;
if (httpEntity!=null) {
BufferedReader reader=null;
try {
reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
String line=null;
while ((line=reader.readLine())!=null) {
entityStringBuilder.append(line);
}
// 从HttpEntity中得到的json String数据转为json
jsonStr=entityStringBuilder.toString();
resultJsonObject=JSON.parseObject(jsonStr);
} catch (JSONException e) {
//如果不是json格式的,应该是表单键值对格式,直接put到formData
resultJsonObject.put("formData",jsonStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
//关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return resultJsonObject;
} /**
* 将httpResponse对象转换为自定义的BaseResponse对象
* @param httpResponse
* @return
*/
public BaseResponse httpResponseToBaseResponse(CloseableHttpResponse httpResponse){
// 遍历取出headers
JSONArray headList = new JSONArray();
for (Header header :httpResponse.getAllHeaders()){
String key = header.getName();
String value = header.getValue();
JSONObject tempJson = new JSONObject();
tempJson.put(key,value);
headList.add(tempJson);
}
BaseResponse baseResponse = new BaseResponse();
baseResponse.setHeaders(headList);
baseResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
baseResponse.setResponseBody(httpEntityToJSONObject(httpResponse.getEntity())); return baseResponse;
} /**
* 为httpGet和httpPost加headers
* @param httpEntityEnclosingRequestBase,HttpGet和HttpPost都是继承这个类
* @param headers
* @return
*/
public HttpEntityEnclosingRequestBase addHeaders(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, JSONObject headers){
//循环加header
if(headers!=null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpEntityEnclosingRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return httpEntityEnclosingRequestBase;
}
/**
* 为httpGet加headers
* @param httpRequestBase,HttpGet和HttpPost都是继承这个类
* @param headers
* @return
*/
public HttpRequestBase addHeaders(HttpRequestBase httpRequestBase, JSONObject headers){
//循环加header
if(headers!=null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return httpRequestBase;
} /**
* 为httpPost加cookies
* @param httpEntityEnclosingRequestBase,HttpPost是继承这个类
* @param cookies
* @return
*/
public HttpEntityEnclosingRequestBase addCookies(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,String cookies){
//循环加cookies
if(cookies!=null) {
httpEntityEnclosingRequestBase.addHeader("Cookie", cookies);
}
return httpEntityEnclosingRequestBase;
}
/**
* 为httpPost加cookies
* @param httpRequestBase,HttpGet是继承这个类
* @param cookies
* @return
*/
public HttpRequestBase addCookies(HttpRequestBase httpRequestBase, String cookies){
//循环加cookies
if(cookies!=null) {
httpRequestBase.addHeader("Cookie", cookies);
}
return httpRequestBase;
} }
 import java.io.*;
import java.net.URL;
import java.net.URLConnection; /**
* @author kin
* @version $: v 0.1 2016/8/23 Exp $$
*/
public class httpTest { public static void sendGet() throws IOException { BufferedReader in1 = null;
// 1.创建URL类
URL urlString = new URL("https://www.baidu.com"); // 2.打开和URL之间的连接
URLConnection connection1 = urlString.openConnection(); // 3.设置通用的请求属性 connection1.setRequestProperty("accept", "*/*");
connection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8;");
connection1.setRequestProperty("connection", "Keep-Alive");
connection1.setRequestProperty("user-agent", "testDemo"); // 4.建立实际的连接
connection1.connect(); // 5.定义 BufferedReader输入流来读取URL的响应
in1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
String line = null;
while ((line = in1.readLine()) != null) {
System.out.println(line);
} // 6.使用finally块来关闭输入流
in1.close();
} public static void sendPost(String data) {
String charSet = "utf-8";
BufferedReader in1 = null;
PrintWriter out = null;
// 1.创建URL类
try {
URL urlPost = new URL("http://www.baidu.com"); // 2.打开和URL之间的连接 URLConnection connectionPost = urlPost.openConnection();
// 3.设置通用的请求属性
connectionPost.setConnectTimeout(30000);
connectionPost.setReadTimeout(30000);
connectionPost.setRequestProperty("accept", "*/*");
connectionPost.setRequestProperty("Content-Type", "application/json;charset=" + charSet);
connectionPost.setRequestProperty("connection", "Keep-Alive");
connectionPost.setRequestProperty("user-agent", "testDemoPost");
// 4.建立实际的连接
connectionPost.connect(); // 5.发送post请求必须设置如下两行,设置了这两行,就可以对URL连接进行输入/输出 connectionPost.setDoInput(true);
connectionPost.setDoOutput(true);
// 6.获取URLConnection对象对应的输出流 out = new PrintWriter(new OutputStreamWriter(connectionPost.getOutputStream(), charSet)); // 7.发送请求参数
out.print(data); // 8.清空缓存区的缓存
out.flush(); // 9.定义 BufferedReader输入流来读取URL的响应
in1 = new BufferedReader(new InputStreamReader(connectionPost.getInputStream(), charSet)); } catch (IOException e) {
e.printStackTrace();
}// 10.使用finally块来关闭输入流
finally {
try {
out.close();
in1.close();
}catch(Exception e){
e.printStackTrace();
} }
}
public static void main(String[] args) throws IOException {
httpTest.sendGet();
} }

最新文章

  1. 详解Eclipse断点
  2. layout
  3. (转)设计模式_Singleton单例模式
  4. [POJ1284]Primitive Roots(原根性质的应用)
  5. python除法
  6. smarty模板原理
  7. CSS3学习(CSS3过渡、CSS3动画)
  8. IEnumerable接口的扩展方法
  9. 磁盘管理三-raid
  10. UIColor,CGColor,CIColor三者间的区别和联系
  11. Xcode-之CocoaPads
  12. 201521123029《Java程序设计》第14周学习总结
  13. 软考论文的六大应对策略V1.0
  14. C# - 代码重构
  15. WebSphere隐藏版本号教程
  16. location search的中文加密
  17. hdu 1.2.5
  18. Node.js实战(十)之EventEmitter
  19. Android Fragment(三)ListFragment简单介绍以及Fragment之间通信
  20. HTML5学习笔记(十八):闭包

热门文章

  1. Javascript的一些经验总结
  2. 51nod 1412 AVL数的种类(DP
  3. Bootstrap历练实例:表单控件大小
  4. windows使用文件服务器搭建Git服务器
  5. luogu P1966 火柴排队 (逆序对)
  6. HDU-1548-奇怪的电梯
  7. 【贪心】bzoj1045: [HAOI2008] 糖果传递
  8. 【贪心 堆】luoguP2672 推销员
  9. RN原生方法setNativeProps
  10. PyCharm 社区版创建Django项目的一个方法