欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中有关HttpClient知识

程序员文章站 2022-06-18 11:27:19
...

Java中有关HttpClient知识

什么是HTTP协议

以下博主写的十分清楚,认真阅读即可。在这里感谢大佬的总结(●’◡’●)

https://www.jianshu.com/p/7c8b4576e4bb

简述几条最基本使用
1.通过TCP套接字,客户端向Web服务器发送一个文本的请求报文,一个请求报文由请求行,请求头部,空行和请求体4个部分构成。
2.在接收到请求之后,服务器经过解释之后,会返回个一个HTTP响应。HTTP响应是由四部分构成:状态行 响应头 空行 响应体。
Java中有关HttpClient知识
以下是几个比较常用到的请求头,大家可以参照引用博主的详情信息打捞基础!
Accept:可接收的响应内容类型
Accept-Charset:可接收的字符集
Accept-Encoding:可接受的响应内容的编码方式 (http协议在传输时的加密方式,如果你的相应总是莫名其妙的乱码,你要对这个地方格外注意)
Content-Type:请求体的MIME类型

具体的代码

一些java中HttpClient的知识已在代码中体现,详情可以仔细阅读代码。

/**
	 * post请求(用于key-value格式的参数)
	 * @param url 请求连接
	 * @param maps 请求数据的集合
	 * @throws Exception
	 */
	public static void postClient(String url , Map<String,String> maps) throws Exception{
		CloseableHttpClient  httpClient = HttpClients.createDefault();	//创建一个可以关闭的Http链接
		HttpPost post = new HttpPost(url);		//这里使用Post方式提交
		//以下是post提交的时候所包含的请求头
		post.addHeader("Authorization", "basic {"+token+"}"); //token为认证所需,对接不同接口形式不同可能不需要
		post.addHeader("Content-Type", "text/xml; charset=utf-8");
		post.addHeader("Accept","application/xml");
		
		//以下是请求时所要post提交的数据
		ArrayList<NameValuePair> resbodyValue = new ArrayList<NameValuePair>();
		for(Map.Entry<String, String> entry : maps.entrySet()){
			String key = entry.getKey();
			String value = entry.getValue();
			resbodyValue.add(new BasicNameValuePair(key,value));
		}
		//post提交时有许多Entity,e.g:StringEntity,BasicHttpEntity,ByteArrayEntity等
		
		post.setEntity(new UrlEncodedFormEntity(resbodyValue,"UTF-8"));	
		
		CloseableHttpResponse response = httpClient.execute(post);//发送请求
		int status = response.getStatusLine().getStatusCode(); // 获取相应状态码 
		BufferedReader in = null;  
		if(status == 200){	//请求成功
         	in = new BufferedReader(new InputStreamReader(response.getEntity()  
                     .getContent(),"utf-8"));
             StringBuffer sb = new StringBuffer("");  
             String line = "";  
             String NL = System.getProperty("line.separator");  
             while ((line = in.readLine()) != null) {  
                 sb.append(line + NL);  
             }
             
             in.close();  
         }
        else{	
         	System.out.println("状态码:" + status);
         }
	}
	
	/**
	 * post请求(用于请求json格式的参数)
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url,String params) throws Exception {
		
		String code = (appId+"&"+appKey);
		
		String token = Base64Utils.encode(code.getBytes());
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost   
    	httpPost.setHeader("Accept", "text/json"); 
    	httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
    	httpPost.setHeader("Accept-Language", "zh-cn");
    	httpPost.setHeader("Authorization", "Basic "+token);
    	String charSet = "UTF-8";
    	StringEntity entity = new StringEntity(params, charSet);
    	httpPost.setEntity(entity);    
    	
        CloseableHttpResponse response = null;
        
        try {
        	
        	response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
            	HttpEntity responseEntity = response.getEntity();
            	String jsonString = EntityUtils.toString(responseEntity);
            	String str = new String(jsonString.getBytes("ISO-8859-1"),"UTF-8");
            	return str;
            }else{
				 logger.error("请求返回:"+state+"("+url+")");
				 System.out.println("请求返回:"+state+"("+url+")");
			}
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return null;
	}
	

Get请求相对于刚才Post请求就简单的很多,毕竟是有了Post的请求的基础了嘛,详见代码:

/**
	 * get请求
	 * @return
	 */
	public static String doGet(String url) {
		String token = Base64Utils.encode((appId+"&"+appKey).getBytes());
        try {
        	HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            request.setHeader("Accept", "text/json"); 
            request.setHeader("Content-Type", "application/json;charset=UTF-8");
            request.setHeader("Accept-Language", "zh-cn");
            request.setHeader("Authorization", "Basic "+token);
            
            HttpResponse response = client.execute(request);
 
            System.out.println(response);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                
                return strResult;
            }
        } 
        catch (IOException e) {
        	e.printStackTrace();
        }
        
        return null;
	}

通过Poxy的方式进行的Http请求,这个一般适用于翻译的**等功能,需要不断的切换IP的场景

 /**
     * 
     * @param ipBean 存放ip的实体
     * @param params 以Key-value的形式进行
     * @return
     */
    public String ProxyTranlate(IPBean ipBean,List<NameValuePair> params){
    	String translateLang = "";

        IPBean ip = IpUtils.getIP();
    	Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip.getIp(), ip.getPort())); //设置代理IP的地址和端口
        try {
            URLConnection httpCon = new URL(PATH).openConnection(proxy);
            httpCon.setConnectTimeout(5000);
            httpCon.setReadTimeout(5000);
            httpCon.setDoOutput(true);
            httpCon.setDoInput(true);
            httpCon.setRequestProperty("User-Agent",USER_AGENT);
            //httpCon.setRequestProperty("accept-encoding","gzip");
            httpCon.setRequestProperty("accept-language","zh-CN,zh;q=0.9");
            //httpCon.setRequestProperty("content-type","application/json; charset=UTF-8");
            OutputStream os = httpCon.getOutputStream(); //获取响应流并解析
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            writer.write(getQuery(params));
            writer.flush();
            writer.close();
            os.close();
            InputStream in = httpCon.getInputStream();  //带资源的try-catch语句。自动关闭
			InputStream buffer = new BufferedInputStream(in);
			// 将InputStream串链到一个Reader
			Reader reader = new InputStreamReader(buffer, "UTF-8");
			int c;
			while ((c = reader.read()) != -1) {
				translateLang += (char) c;
			}
			reader.close();
			buffer.close();
			in.close();
			System.out.println(ip);
            return translateLang;
        } catch (IOException e) {
        	if(e.getMessage().indexOf("proxy")==-1){
        		e.printStackTrace();
            	IpUtils.removeIp(ip);
            	return "error";
        	}else{
        		e.printStackTrace();
        		return "404";
        	}
        }
    }

文章仅供参考,旨为学习参考,如果有什么不对的地方请大家多多指教,必当及时更正!