1. 程式人生 > >Java發送http get/post請求,調用接口/方法

Java發送http get/post請求,調用接口/方法

strong org 釋放 github string charset 獲取url lean catch

由於項目中要用,所以找了一些資料,整理下來。

GitHub地址: https://github.com/iamyong 轉自:http://blog.csdn.net/capmiachael/article/details/51833531

例1:使用 HttpClient (commons-httpclient-3.0.jar

 1 import java.io.ByteArrayInputStream;
 2 import java.io.ByteArrayOutputStream;
 3 import java.io.IOException;
 4 import java.io.InputStream;
5 6 import org.apache.commons.httpclient.HttpClient; 7 import org.apache.commons.httpclient.methods.InputStreamRequestEntity; 8 import org.apache.commons.httpclient.methods.PostMethod; 9 import org.apache.commons.httpclient.methods.RequestEntity; 10 11 public class HttpTool { 12 13 /** 14 * 發送post請求
15 * 16 * @param params 17 * 參數 18 * @param requestUrl 19 * 請求地址 20 * @param authorization 21 * 授權書 22 * @return 返回結果 23 * @throws IOException 24 */ 25 public static String sendPost(String params, String requestUrl,
26 String authorization) throws IOException { 27 28 byte[] requestBytes = params.getBytes("utf-8"); // 將參數轉為二進制流 29 HttpClient httpClient = new HttpClient();// 客戶端實例化 30 PostMethod postMethod = new PostMethod(requestUrl); 31 //設置請求頭Authorization 32 postMethod.setRequestHeader("Authorization", "Basic " + authorization); 33 // 設置請求頭 Content-Type 34 postMethod.setRequestHeader("Content-Type", "application/json"); 35 InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, 36 requestBytes.length); 37 RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, 38 requestBytes.length, "application/json; charset=utf-8"); // 請求體 39 postMethod.setRequestEntity(requestEntity); 40 httpClient.executeMethod(postMethod);// 執行請求 41 InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 獲取返回的流 42 byte[] datas = null; 43 try { 44 datas = readInputStream(soapResponseStream);// 從輸入流中讀取數據 45 } catch (Exception e) { 46 e.printStackTrace(); 47 } 48 String result = new String(datas, "UTF-8");// 將二進制流轉為String 49 // 打印返回結果 50 // System.out.println(result); 51 52 return result; 53 54 } 55 56 /** 57 * 從輸入流中讀取數據 58 * 59 * @param inStream 60 * @return 61 * @throws Exception 62 */ 63 public static byte[] readInputStream(InputStream inStream) throws Exception { 64 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 65 byte[] buffer = new byte[1024]; 66 int len = 0; 67 while ((len = inStream.read(buffer)) != -1) { 68 outStream.write(buffer, 0, len); 69 } 70 byte[] data = outStream.toByteArray(); 71 outStream.close(); 72 inStream.close(); 73 return data; 74 } 75 }

例2:

  1 import java.io.BufferedReader;  
  2 import java.io.IOException;
  3 import java.io.InputStream;  
  4 import java.io.InputStreamReader;  
  5 import java.io.OutputStreamWriter;
  6 import java.io.UnsupportedEncodingException;  
  7 import java.net.HttpURLConnection;  
  8 import java.net.InetSocketAddress;
  9 import java.net.Proxy;
 10 import java.net.URL; 
 11 import java.net.URLConnection;
 12 import java.util.List;
 13 import java.util.Map;
 14 
 15 /** 
 16  * Http請求工具類 
 17  */
 18 public class HttpRequestUtil {
 19     static boolean proxySet = false;
 20     static String proxyHost = "127.0.0.1";
 21     static int proxyPort = 8087;
 22     /** 
 23      * 編碼 
 24      * @param source 
 25      * @return 
 26      */ 
 27     public static String urlEncode(String source,String encode) {  
 28         String result = source;  
 29         try {  
 30             result = java.net.URLEncoder.encode(source,encode);  
 31         } catch (UnsupportedEncodingException e) {  
 32             e.printStackTrace();  
 33             return "0";  
 34         }  
 35         return result;  
 36     }
 37     public static String urlEncodeGBK(String source) {  
 38         String result = source;  
 39         try {  
 40             result = java.net.URLEncoder.encode(source,"GBK");  
 41         } catch (UnsupportedEncodingException e) {  
 42             e.printStackTrace();  
 43             return "0";  
 44         }  
 45         return result;  
 46     }
 47     /** 
 48      * 發起http請求獲取返回結果 
 49      * @param req_url 請求地址 
 50      * @return 
 51      */ 
 52     public static String httpRequest(String req_url) {
 53         StringBuffer buffer = new StringBuffer();  
 54         try {  
 55             URL url = new URL(req_url);  
 56             HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
 57 
 58             httpUrlConn.setDoOutput(false);  
 59             httpUrlConn.setDoInput(true);  
 60             httpUrlConn.setUseCaches(false);  
 61 
 62             httpUrlConn.setRequestMethod("GET");  
 63             httpUrlConn.connect();  
 64 
 65             // 將返回的輸入流轉換成字符串  
 66             InputStream inputStream = httpUrlConn.getInputStream();  
 67             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
 68             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
 69 
 70             String str = null;  
 71             while ((str = bufferedReader.readLine()) != null) {  
 72                 buffer.append(str);  
 73             }  
 74             bufferedReader.close();  
 75             inputStreamReader.close();  
 76             // 釋放資源  
 77             inputStream.close();  
 78             inputStream = null;  
 79             httpUrlConn.disconnect();  
 80 
 81         } catch (Exception e) {  
 82             System.out.println(e.getStackTrace());  
 83         }  
 84         return buffer.toString();  
 85     }  
 86 
 87     /** 
 88      * 發送http請求取得返回的輸入流 
 89      * @param requestUrl 請求地址 
 90      * @return InputStream 
 91      */ 
 92     public static InputStream httpRequestIO(String requestUrl) {  
 93         InputStream inputStream = null;  
 94         try {  
 95             URL url = new URL(requestUrl);  
 96             HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
 97             httpUrlConn.setDoInput(true);  
 98             httpUrlConn.setRequestMethod("GET");  
 99             httpUrlConn.connect();  
100             // 獲得返回的輸入流  
101             inputStream = httpUrlConn.getInputStream();  
102         } catch (Exception e) {  
103             e.printStackTrace();  
104         }  
105         return inputStream;  
106     }
107 
108 
109     /**
110      * 向指定URL發送GET方法的請求
111      * 
112      * @param url
113      *            發送請求的URL
114      * @param param
115      *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
116      * @return URL 所代表遠程資源的響應結果
117      */
118     public static String sendGet(String url, String param) {
119         String result = "";
120         BufferedReader in = null;
121         try {
122             String urlNameString = url + "?" + param;
123             URL realUrl = new URL(urlNameString);
124             // 打開和URL之間的連接
125             URLConnection connection = realUrl.openConnection();
126             // 設置通用的請求屬性
127             connection.setRequestProperty("accept", "*/*");
128             connection.setRequestProperty("connection", "Keep-Alive");
129             connection.setRequestProperty("user-agent",
130                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
131             // 建立實際的連接
132             connection.connect();
133             // 獲取所有響應頭字段
134             Map<String, List<String>> map = connection.getHeaderFields();
135             // 遍歷所有的響應頭字段
136             for (String key : map.keySet()) {
137                 System.out.println(key + "--->" + map.get(key));
138             }
139             // 定義 BufferedReader輸入流來讀取URL的響應
140             in = new BufferedReader(new InputStreamReader(
141                     connection.getInputStream()));
142             String line;
143             while ((line = in.readLine()) != null) {
144                 result += line;
145             }
146         } catch (Exception e) {
147             System.out.println("發送GET請求出現異常!" + e);
148             e.printStackTrace();
149         }
150         // 使用finally塊來關閉輸入流
151         finally {
152             try {
153                 if (in != null) {
154                     in.close();
155                 }
156             } catch (Exception e2) {
157                 e2.printStackTrace();
158             }
159         }
160         return result;
161     }
162 
163     /**
164      * 向指定 URL 發送POST方法的請求
165      * 
166      * @param url
167      *            發送請求的 URL
168      * @param param
169      *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
170      * @param isproxy
171      *               是否使用代理模式
172      * @return 所代表遠程資源的響應結果
173      */
174     public static String sendPost(String url, String param,boolean isproxy) {
175         OutputStreamWriter out = null;
176         BufferedReader in = null;
177         String result = "";
178         try {
179             URL realUrl = new URL(url);
180             HttpURLConnection conn = null;
181             if(isproxy){//使用代理模式
182                 @SuppressWarnings("static-access")
183                 Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
184                 conn = (HttpURLConnection) realUrl.openConnection(proxy);
185             }else{
186                 conn = (HttpURLConnection) realUrl.openConnection();
187             }
188             // 打開和URL之間的連接
189 
190             // 發送POST請求必須設置如下兩行
191             conn.setDoOutput(true);
192             conn.setDoInput(true);
193             conn.setRequestMethod("POST");    // POST方法
194 
195 
196             // 設置通用的請求屬性
197 
198             conn.setRequestProperty("accept", "*/*");
199             conn.setRequestProperty("connection", "Keep-Alive");
200             conn.setRequestProperty("user-agent",
201                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
202             conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
203 
204             conn.connect();
205 
206             // 獲取URLConnection對象對應的輸出流
207             out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
208             // 發送請求參數
209             out.write(param);
210             // flush輸出流的緩沖
211             out.flush();
212             // 定義BufferedReader輸入流來讀取URL的響應
213             in = new BufferedReader(
214                     new InputStreamReader(conn.getInputStream()));
215             String line;
216             while ((line = in.readLine()) != null) {
217                 result += line;
218             }
219         } catch (Exception e) {
220             System.out.println("發送 POST 請求出現異常!"+e);
221             e.printStackTrace();
222         }
223         //使用finally塊來關閉輸出流、輸入流
224         finally{
225             try{
226                 if(out!=null){
227                     out.close();
228                 }
229                 if(in!=null){
230                     in.close();
231                 }
232             }
233             catch(IOException ex){
234                 ex.printStackTrace();
235             }
236         }
237         return result;
238     }    
239 
240     public static void main(String[] args) {
241         //demo:代理訪問
242         String url = "http://api.adf.ly/api.php";
243         String para = "key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
244 
245         String sr=HttpRequestUtil.sendPost(url,para,true);
246         System.out.println(sr);
247     }
248 
249 }

例3

 1 /**
 2      * 發送Http post請求
 3      * 
 4      * @param xmlInfo
 5      *            json轉化成的字符串
 6      * @param URL
 7      *            請求url
 8      * @return 返回信息
 9      */
10     public static String doHttpPost(String xmlInfo, String URL) {
11         System.out.println("發起的數據:" + xmlInfo);
12         byte[] xmlData = xmlInfo.getBytes();
13         InputStream instr = null;
14         java.io.ByteArrayOutputStream out = null;
15         try {
16             URL url = new URL(URL);
17             URLConnection urlCon = url.openConnection();
18             urlCon.setDoOutput(true);
19             urlCon.setDoInput(true);
20             urlCon.setUseCaches(false);
21             urlCon.setRequestProperty("content-Type", "application/json");
22             urlCon.setRequestProperty("charset", "utf-8");
23             urlCon.setRequestProperty("Content-length",
24                     String.valueOf(xmlData.length));
25             System.out.println(String.valueOf(xmlData.length));
26             DataOutputStream printout = new DataOutputStream(
27                     urlCon.getOutputStream());
28             printout.write(xmlData);
29             printout.flush();
30             printout.close();
31             instr = urlCon.getInputStream();
32             byte[] bis = IOUtils.toByteArray(instr);
33             String ResponseString = new String(bis, "UTF-8");
34             if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
35                 System.out.println("返回空");
36             }
37             System.out.println("返回數據為:" + ResponseString);
38             return ResponseString;
39 
40         } catch (Exception e) {
41             e.printStackTrace();
42             return "0";
43         } finally {
44             try {
45                 out.close();
46                 instr.close();
47 
48             } catch (Exception ex) {
49                 return "0";
50             }
51         }
52     }

Java發送http get/post請求,調用接口/方法