HttpURLConnection类 与HttpClient模拟向服务器发送请求

本文会以两个三方接口作为示例

 案例一:在某个项目由于要获得用户登录真实IP的省市区信息,调用淘宝API接口获得使用JDK的net包下自带   HttpUrlConnection发送请求

代码如下,有详细注释请自行参阅:

package com.niuniu.core.util.Address;
import java.io.BufferedReader;  
import java.io.DataOutputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
import java.net.HttpURLConnection;  
import java.net.URL;

import com.alibaba.fastjson.JSONObject;  
  
/**
 * 
 * @Description:根据IP地址获取详细的地域信息 -http://ip.taobao.com/service/getIpInfo.php?ip=xxx.xx.xxx.xx
 * @author:tuizhi-cai
 * @time:2018年1月30日 下午5:53:35
 */
public class AddressUtils {  
    /** 
     *  
     * @param content  请求的参数 格式为:name=xxx&pwd=xxx 
     * @param encoding 服务器端请求编码。如GBK,UTF-8等 
     * @Param 淘宝查询IP接口
     */  
    public static String getAddresses(String content, String encodingString,String urlStr)  
            throws UnsupportedEncodingException {  
        // 这里调用淘宝API  
        String returnStr = getResult(urlStr, content, encodingString);  
        if (returnStr != null) {  
            // 处理返回的省市区信息  
            returnStr = decodeUnicode(returnStr);  
            String[] temp = returnStr.split(",");  
            if(temp.length<3){  
                return null;//无效IP,局域网测试  
            }  
            return returnStr;  
        }  
        return null;  
    }  
    /** 
     * @param urlStr  请求的地址 
     */  
    private static String getResult(String urlStr, String content, String encoding) {  
        URL url = null;  
        HttpURLConnection connection = null;  
        try {  
            url = new URL(urlStr);  
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例  
            connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒  
            connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒  
            connection.setDoOutput(true);// 是否打开输出流 true|false  
            connection.setDoInput(true);// 是否打开输入流true|false  
            connection.setRequestMethod("POST");// 提交方法POST|GET  
            connection.setUseCaches(false);// 是否缓存true|false  
            connection.connect();// 打开连接端口  
            DataOutputStream out = new DataOutputStream(connection  
                    .getOutputStream());// 打开输出流往对端服务器写数据  
            out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx  
            out.flush();// 刷新  
            out.close();// 关闭输出流  
            BufferedReader reader = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据  
            // ,以BufferedReader流来读取  
            StringBuffer buffer = new StringBuffer();  
            String line = "";  
            while ((line = reader.readLine()) != null) {  
                buffer.append(line);  
            }  
            reader.close();  
            return buffer.toString();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (connection != null) {  
                connection.disconnect();// 关闭连接  
            }  
        }  
        return null;  
    }  
    /** 
     * unicode 转换成 中文 
     */  
    public static String decodeUnicode(String theString) {  
        char aChar;  
        int len = theString.length();  
        StringBuffer outBuffer = new StringBuffer(len);  
        for (int x = 0; x < len;) {  
            aChar = theString.charAt(x++);  
            if (aChar == '\\') {  
                aChar = theString.charAt(x++);  
                if (aChar == 'u') {  
                    int value = 0;  
                    for (int i = 0; i < 4; i++) {  
                        aChar = theString.charAt(x++);  
                        switch (aChar) {  
                        case '0':  
                        case '1':  
                        case '2':  
                        case '3':  
                        case '4':  
                        case '5':  
                        case '6':  
                        case '7':  
                        case '8':  
                        case '9':  
                            value = (value << 4) + aChar - '0';  
                            break;  
                        case 'a':  
                        case 'b':  
                        case 'c':  
                        case 'd':  
                        case 'e':  
                        case 'f':  
                            value = (value << 4) + 10 + aChar - 'a';  
                            break;  
                        case 'A':  
                        case 'B':  
                        case 'C':  
                        case 'D':  
                        case 'E':  
                        case 'F':  
                            value = (value << 4) + 10 + aChar - 'A';  
                            break;  
                        default:  
                            throw new IllegalArgumentException(  
                                    "无法解析的字符码,在addressUtils中");  
                        }  
                    }  
                    outBuffer.append((char) value);  
                } else {  
                    if (aChar == 't') {  
                        aChar = '\t';  
                    } else if (aChar == 'r') {  
                        aChar = '\r';  
                    } else if (aChar == 'n') {  
                        aChar = '\n';  
                    } else if (aChar == 'f') {  
                        aChar = '\f';  
                    }  
                    outBuffer.append(aChar);  
                }  
            } else {  
                outBuffer.append(aChar);  
            }  
        }  
        return outBuffer.toString();  
    }  
    
    
  /*  public static void main(String[] args) {
    	  // 参数ip  
//      String ip = "219.136.134.157";  
        String ip = "221.235.44.19";  
          
        // json_result用于接收返回的json数据  
        String json_result = null;  
        try {  
            json_result = AddressUtils.getAddresses("ip=" + ip, "utf-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        JSONObject json = JSONObject.fromObject(json_result);  
        System.out.println("json数据: " + json);  
        String country = JSONObject.fromObject(json.get("data")).get("country").toString();  
        String region = JSONObject.fromObject(json.get("data")).get("region").toString();  
        String city = JSONObject.fromObject(json.get("data")).get("city").toString();  
        String county = JSONObject.fromObject(json.get("data")).get("county").toString();  
        String isp = JSONObject.fromObject(json.get("data")).get("isp").toString();  
        String area = JSONObject.fromObject(json.get("data")).get("area").toString();  
        System.out.println("国家: " + country);  
        System.out.println("地区: " + area);  
        System.out.println("省份: " + region);  
        System.out.println("城市: " + city);  
        System.out.println("区/县: " + county);  
        System.out.println("互联网服务提供商: " + isp);  
          
        String address = country + "/";  
        address += region + "/";  
        address += city + "/";  
        address += county;  
        System.out.println(address); 
	}*/
} 

案例二:使用HttpClient调用第三方接口,并接收返回信息,

/**
 * 
 */
package com.niuniu.core.util.httpclient;

import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils.Null;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.Video;

/**
 * @Description:
 * @author:tuizhi-cai
 * @time:2018年2月6日 下午6:43:59
 */
public class HttpClient {

	private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
	
	
	/**
	 * @throws Exception 
	 * @Author:tuzhi-cai
	 * @param url : 请求的url
	 * @param contenType :请求头类型(不是必须)
	 * @Param reponseType :设置响应格式(不是必须)
	 * @Description: 发送get请求
	 * @time:2018年2月6日下午6:44:36
	 */
	@SuppressWarnings("unused")
	public static String sendGet(String url,String contentType,String responseType) {
		CloseableHttpClient httpClient =null;
		HttpGet httpGet = null;
		try {
			httpClient = HttpClients.createDefault();//创建一个httpClient
			httpGet = new HttpGet(url); //创建一个get请求
			HttpResponse response = httpClient.execute(httpGet);//执行get请求返回数据
			if (contentType!=""&&contentType!=null) {
				httpGet.setHeader("Content-Type",contentType);
			}
			if (responseType!=""&&responseType!=null) {
				httpGet.setHeader("Accept-Encoding",responseType ); //设置响应格式"application/json","gzip, deflate"
			}
			//如果返回的是普通字符串的格式执行
			String result = "";   
			HttpEntity httpEntity = response.getEntity();//拿到返回的实体数据
			if (httpEntity!=null) {
				result = EntityUtils.toString(httpEntity, "utf-8");
			}
			EntityUtils.consume(httpEntity); //释放实体对象
			httpGet.releaseConnection();//关闭链接
			httpGet.releaseConnection();//释放链接
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			httpGet.releaseConnection();
			logger.error("魔盒数据获取错误",e);
			return null;
		}
	}
	
	
	/**
	 * @Author:tuzhi-cai
	 * @param url :请求的url
	 * @Param paraMap :请求参数
	 * @param contentType :请求头类型(不是必须)
	 * @param reponseType :设置响应数据格式(不是必须)
	 * @Description: 发送post请求
	 * @time:2018年2月6日下午6:45:07
	 */
	@SuppressWarnings("unused")
	public static String sendPost(String url,Map<String,String> paramMap ,String contentType,String responseType){
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = "" ; //返回的结果集
        try {
        	httpClient = HttpClients.createDefault();
        	httpPost = new HttpPost(url);
        	if (contentType!=""&&contentType!=null) {
				httpPost.setHeader("Content-Type",contentType); //"application/json;charset=utf-8"...application/x-www-form-urlencoded
			}
        	if (responseType!=""&&responseType!=null) {
        		httpPost.setHeader("Accept-Encoding", contentType);
        	}
        	//设置参数:建立一个NameValuePair数组,用于存储准备传送的参数
        	List<NameValuePair> params = new ArrayList<NameValuePair>();
        	if (paramMap!=null&¶mMap.keySet().size()!=0) { //如果传送的参数不为空
				for (Entry<String, String> paramKeyValue : paramMap.entrySet()) {
					params.add(new BasicNameValuePair(paramKeyValue.getKey(), paramKeyValue.getValue()));
				}
			}
        		//将参数添加到请求对象中,并指定字符编码
        	httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8")); 
        		//执行httpPost请求并拿到结果(同步阻塞)
        	CloseableHttpResponse response = httpClient.execute(httpPost);
        		//如果返回的是普通字符串的格式执行
        	HttpEntity entity = response.getEntity();
        	if (entity!=null) {
        		result = EntityUtils.toString(entity, "utf-8");
        	}
        	EntityUtils.consume(entity); //释放实体对象
        	httpPost.releaseConnection();//释放链接
        	return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("魔盒数据获取错误",e);
			httpPost.releaseConnection();
			return "";//返回null
		}
	}
	
	
	
	/**
	 * 	HttpResponse response = httpClient.execute(httpPost);
	 *	//获取遍历取头信息
	 *	Header[] headers = response.getAllHeaders();
	 *	for(int i=0;i<headers.length;i++) {
	 *	   System.out.println(headers[i].getName() +"=="+ headers[i].getValue());
	 * }
	 */
	

	
	/**
	 * 
	 * @Author:tuzhi-cai
	 * @Description: 魔盒对返回报告数据进行压缩,解压缩
	 * @time:2018年2月7日上午10:54:12
	 */
	@SuppressWarnings({ "unused", "restriction" })
	public static String gunzip(String compressStr){
		 ByteArrayOutputStream byteArrayOut= new ByteArrayOutputStream(); //创建二进制输出流
		 ByteArrayInputStream  byteArrayIn=null; //二进制输入流
		 GZIPInputStream zipInput=null; //zip输入流
		 byte[] byteCompressed=null;
		 String deCompressed = null;
		 try {	
			 //对返回数据字符串BASE64解码 ,返回byte数组
		     byteCompressed = new sun.misc.BASE64Decoder().decodeBuffer(compressStr); 
		     byteArrayIn=new ByteArrayInputStream(byteCompressed); //传入二进制输入流
		     zipInput=new GZIPInputStream( byteArrayIn); //传入zip输入流
		     // 解码后对数据gzip解压缩
		     byte[] buffer = new byte[1024];
		     int isHasStringSize = -1;
		     //一次读取1024长度的byte数组
		     while ((isHasStringSize = zipInput.read(buffer)) != -1) { 
		    	 //每次写出实际长度的byte数组
		    	 byteArrayOut.write(buffer, 0, isHasStringSize);  
		     }
		     // 转换为字符串,并对数据进行utf-8转码         
		     deCompressed = byteArrayOut.toString("utf-8"); 
		     return deCompressed;
		 } catch (Exception e) {
			 e.printStackTrace();
			 logger.error("解压报告数据失败", e);
			 return deCompressed;
		 }
	}
	
	
	
	public static void main(String[] args) {
		
		//接口地址
		String url = "https://api.shujumohe.com/octopus/report.task.query/v2?partner_code=nngj_mohe&partner_key=856c34e00d154d809bc094535a786101";
				//TASKYYS100000201802071028530331920498
	    Map<String, String> map = new HashMap<>();
	    map.put("task_id", "TASKYYS100000201802071028530331920498");
	    map.put("real_name","蔡展鹏");
	    //返回结果集
	  //  String result = sendPost(url, map, "application/x-www-form-urlencoded; charset=UTF-8", "*/*");
	      String result = sendPost(url, map, null, null);
	    JSONObject json = JSON.parseObject(result); 
	    String data = json.getString("data");
	    System.out.println(json.getString("code")+"是否字符串");
	    String decompressed =  gunzip(data);
	    System.out.println(result);
	    System.out.println("解析成功``````151```"+decompressed);

	}
	
	

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnectionHttpClient库来模拟HTTP请求,实现登录系统并获取请求的JSON数据。 使用HttpURLConnection进行模拟HTTP请求,可以按照以下步骤进行操作: 1. 导入相关的包:import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; 2. 创建URL对象,指定要发送请求的URL地址:URL url = new URL("http://example.com/login"); 3. 打开连接,获取HttpURLConnection对象:HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 4. 设置请求的方法为POST:connection.setRequestMethod("POST"); 5. 设置请求的头部信息(如果需要):connection.setRequestProperty("Content-Type", "application/json"); 6. 设置是否允许输入输出:connection.setDoInput(true); connection.setDoOutput(true); 7. 构造请求数据,并发送请求:String requestData = "{\"username\":\"your_username\", \"password\":\"your_password\"}"; OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestData.getBytes("UTF-8")); outputStream.close(); 8. 获取响应的数据:int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); String jsonResponse = response.toString(); // 响应的JSON数据 } 使用HttpClient库进行模拟HTTP请求,可以按照以下步骤进行操作: 1. 导入相关的包:import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; 2. 创建HttpClient对象:HttpClient httpClient = HttpClientBuilder.create().build(); 3. 创建HttpPost对象,指定要发送请求的URL地址:HttpPost httpPost = new HttpPost("http://example.com/login"); 4. 设置请求的头部信息(如果需要):httpPost.setHeader("Content-Type", "application/json"); 5. 构造请求数据,并设置到HttpPost对象中:String requestData = "{\"username\":\"your_username\", \"password\":\"your_password\"}"; StringEntity requestEntity = new StringEntity(requestData, "UTF-8"); httpPost.setEntity(requestEntity); 6. 发送请求,并获取响应:HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String jsonResponse = EntityUtils.toString(responseEntity, "UTF-8"); // 响应的JSON数据 以上是使用Java模拟HTTP请求、登录系统并获取请求的JSON数据的简单示例。根据具体的需求和情况,还可以根据服务器的要求设置其他的请求头部信息,处理响应的状态码等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值