已知两种方法。一种是通过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()+" "; } 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()+" "; } log.info("请求headers信息: "+headerList.substring(0,headerList.length()-2)); // httpPost.addHeader("Content-Type","application/json"); // 为HttpPost设置实体数据 httpPost.setEntity(entity); log.info("请求body: "+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()+" "; } log.info("返回headers信息: "+repheaderList.substring(0,repheaderList.length()-2)); log.info("返回body: "+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()+" "; } log.info("请求headers信息: "+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()+" "; } log.info("返回headers信息: "+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()+" "; } log.info("请求headers信息: "+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()+" "; } log.info("返回headers信息: "+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; } }
1 import java.io.*; 2 import java.net.URL; 3 import java.net.URLConnection; 4 5 /** 6 * @author kin 7 * @version $: v 0.1 2016/8/23 Exp $$ 8 */ 9 public class httpTest { 10 11 public static void sendGet() throws IOException { 12 13 BufferedReader in1 = null; 14 // 1.创建URL类 15 URL urlString = new URL("https://www.baidu.com"); 16 17 18 // 2.打开和URL之间的连接 19 URLConnection connection1 = urlString.openConnection(); 20 21 22 // 3.设置通用的请求属性 23 24 connection1.setRequestProperty("accept", "*/*"); 25 connection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8;"); 26 connection1.setRequestProperty("connection", "Keep-Alive"); 27 connection1.setRequestProperty("user-agent", "testDemo"); 28 29 // 4.建立实际的连接 30 connection1.connect(); 31 32 // 5.定义 BufferedReader输入流来读取URL的响应 33 in1 = new BufferedReader(new InputStreamReader(connection1.getInputStream())); 34 String line = null; 35 while ((line = in1.readLine()) != null) { 36 System.out.println(line); 37 } 38 39 // 6.使用finally块来关闭输入流 40 in1.close(); 41 } 42 43 public static void sendPost(String data) { 44 String charSet = "utf-8"; 45 BufferedReader in1 = null; 46 PrintWriter out = null; 47 // 1.创建URL类 48 try { 49 URL urlPost = new URL("http://www.baidu.com"); 50 51 // 2.打开和URL之间的连接 52 53 URLConnection connectionPost = urlPost.openConnection(); 54 // 3.设置通用的请求属性 55 connectionPost.setConnectTimeout(30000); 56 connectionPost.setReadTimeout(30000); 57 connectionPost.setRequestProperty("accept", "*/*"); 58 connectionPost.setRequestProperty("Content-Type", "application/json;charset=" + charSet); 59 connectionPost.setRequestProperty("connection", "Keep-Alive"); 60 connectionPost.setRequestProperty("user-agent", "testDemoPost"); 61 // 4.建立实际的连接 62 connectionPost.connect(); 63 64 // 5.发送post请求必须设置如下两行,设置了这两行,就可以对URL连接进行输入/输出 65 66 connectionPost.setDoInput(true); 67 connectionPost.setDoOutput(true); 68 // 6.获取URLConnection对象对应的输出流 69 70 out = new PrintWriter(new OutputStreamWriter(connectionPost.getOutputStream(), charSet)); 71 72 // 7.发送请求参数 73 out.print(data); 74 75 // 8.清空缓存区的缓存 76 out.flush(); 77 78 // 9.定义 BufferedReader输入流来读取URL的响应 79 in1 = new BufferedReader(new InputStreamReader(connectionPost.getInputStream(), charSet)); 80 81 82 } catch (IOException e) { 83 e.printStackTrace(); 84 }// 10.使用finally块来关闭输入流 85 finally { 86 try { 87 out.close(); 88 in1.close(); 89 }catch(Exception e){ 90 e.printStackTrace(); 91 } 92 93 } 94 } 95 public static void main(String[] args) throws IOException { 96 httpTest.sendGet(); 97 } 98 99 }