1. 程式人生 > >Java總結之http介面方式

Java總結之http介面方式

目錄

前言

1.Java提供的HttpUrlConnection

2.apacha提供的httpClient


前言

   在實際開發中,我們經常要呼叫其他應用開放的介面,如果

1.Java提供的HttpUrlConnection

package com.inspur.OKHTTP;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Tset{
 
	 /**
     * 呼叫對方介面方法
     * @param path 對方或第三方提供的路徑
     * @param data 向對方或第三方傳送的資料,大多數情況下給對方傳送JSON資料讓對方解析
     */
    public static void httpTest(String path,String data) {
        try {
            URL url = new URL(path);
            //開啟和url之間的連線
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            
            /**設定URLConnection的引數和普通的請求屬性****start***/
           
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
            
            /**設定URLConnection的引數和普通的請求屬性****end***/
            
            //設定是否向httpUrlConnection輸出,設定是否從httpUrlConnection讀入,此外發送post請求必須設定這兩個
            //最常用的Http請求無非是get和post,get請求可以獲取靜態頁面,也可以把引數放在URL字串後面,傳遞給servlet,
            //post與get的 不同之處在於post的引數不是放在URL字串裡面,而是放在http請求的正文內。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            conn.setRequestMethod("GET");//GET和POST必須全大寫
            /**GET方法請求*****start*/
            /**
             * 如果只是傳送GET方式請求,使用connet方法建立和遠端資源之間的實際連線即可;
             * 如果傳送POST方式的請求,需要獲取URLConnection例項對應的輸出流來發送請求引數。
             * */
            conn.connect(); 
            
            /**GET方法請求*****end*/
            
            /***POST方法請求****start*/
            
            /*out = new PrintWriter(conn.getOutputStream());//獲取URLConnection物件對應的輸出流 
            
            out.print(data);//傳送請求引數即資料
            
            out.flush();//緩衝資料
            */            
            /***POST方法請求****end*/
            
            //獲取URLConnection物件對應的輸入流
            InputStream is = conn.getInputStream();
            //構造一個字元流快取
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
            	str=new String(str.getBytes(),"UTF-8");//解決中文亂碼問題
                System.out.println(str);
            }
            //關閉流
            is.close();
            //斷開連線,最好寫上,disconnect是在底層tcp socket連結空閒時才切斷。如果正在被其他執行緒使用就不切斷。
            //固定多執行緒的話,如果不disconnect,連結會增多,直到收發不出資訊。寫上disconnect後正常一些。
            conn.disconnect();
            System.out.println("完整結束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
    	//get請求
    	httpTest("http://******:8080/demo/login/login.do?account=8888888&name=99999999", "");
       
       //post請求
       httpTest("http://******:8080/demo/login/login.do","id=8888888&name=99999999");

    }
 
}

2.apacha提供的httpClient

package org.eking.framework.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	
	/** 
     * 傳送get請求 
     * @param url 
     * @return 
	 * @throws IOException 
	 * @throws ClientProtocolException 
     */  
    public static String getGetResponse(String url) throws ClientProtocolException, IOException {  
    	HttpClient httpClient = HttpClientBuilder.create().build();
    	HttpGet httpGet=new HttpGet(url);
    	HttpResponse httpResponse = httpClient.execute(httpGet);
    	HttpEntity responseEntity = httpResponse.getEntity();  
    	return EntityUtils.toString(responseEntity, "UTF-8"); 
    }  
	
	public static String getPostJsonResponse(String url,String body) 
			throws ClientProtocolException, IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8"); 
    }
	
	public static String getPostJsonResponse(String url,HttpEntity requestEtity ) 
			throws ClientProtocolException, IOException {
       // HttpClient httpClient = HttpClients.createDefault();
        HttpClient httpClient = HttpClientBuilder.create() .build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(requestEtity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        return  EntityUtils.toString(responseEntity, "UTF-8");
    }
	
	
	public static String getPostResponse(String url) 
			throws ClientProtocolException, IOException {
		HttpClient httpClient = HttpClientBuilder.create() .build();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8"); 
    }
}