由于项目中要用,所以找了一些资料,整理下来。
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 }
时间: 2024-10-11 11:49:06