目錄
前言
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");
}
}