欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java HTTP请求,

来源: javaer 分享于  点击 27829 次 点评:276

Java HTTP请求,


方案一(网络):package com.beibei.customer.common;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;
public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url 发送请求的URL * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { return ""; } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { return ""; } } return result; }
/** * 向指定 URL 发送POST方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }}方案二(bb):package com.beibei.customer.utils;
import java.util.ArrayList;import java.util.List;import java.util.Map;
import org.apache.commons.io.IOUtils;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;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.client.methods.HttpRequestBase;import org.apache.http.conn.routing.HttpRoute;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicHeader;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.StringUtils;
/** * @author xiuye.guo * */public class HttpClientUtils {
private static final Logger logger = LoggerFactory .getLogger(HttpClientUtils.class);
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(100); // Increase max connections for localhost:80 to 50 HttpHost localhost = new HttpHost("locahost", 100); cm.setMaxPerRoute(new HttpRoute(localhost), 100);
RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(1000) .setConnectTimeout(1000) .setConnectionRequestTimeout(1000) .build();
httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
}
private static String request(HttpRequestBase httpRequest, List<Header> headers, List<NameValuePair> nvps) {
String result = ""; CloseableHttpResponse response = null;
try { if (headers != null && !headers.isEmpty()) { for (Header header : headers) { httpRequest.addHeader(header); } }
if (nvps != null && !nvps.isEmpty() && httpRequest instanceof HttpPost) { ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity( nvps,"utf-8")); }
response = httpClient.execute(httpRequest);
if (null != response.getStatusLine() && HttpStatus.SC_OK == response.getStatusLine() .getStatusCode()) { HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity); } else { logger.error("Failed to invoke with post request: " + httpRequest.getURI() + "\n-------------\n" + response + "\n\n" + response); }
} catch (Exception e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(response); }
return result; }
public static String postForm(String url, Map<String, String> headerMap, Map<String, String> bodyMap) { List<Header> headers = new ArrayList<Header>(); if (headerMap != null && !headerMap.isEmpty()) { for (String headerKey : headerMap.keySet()) { headers.add(new BasicHeader(headerKey, headerMap.get(headerKey))); } }
List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (bodyMap != null && !bodyMap.isEmpty()) { for (String bodyKey : bodyMap.keySet()) { nvps.add(new BasicNameValuePair(bodyKey, bodyMap.get(bodyKey))); } }
return request(new HttpPost(url), headers, nvps);
}
public static String post(String url, List<Header> headers, List<NameValuePair> nvps) {
return request(new HttpPost(url), headers, nvps); }
public static String postJson(String url, List<Header> headers, String json) { String result = ""; if (StringUtils.isEmpty(url) || StringUtils.isEmpty(json)) { return result; } CloseableHttpResponse response = null; try { HttpPost post = new HttpPost(url);
if (headers != null && !headers.isEmpty()) { for (Header header : headers) { post.addHeader(header); } }
StringEntity entity = new StringEntity(json.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity);
response = httpClient.execute(post);
if (null != response.getStatusLine() && (HttpStatus.SC_OK == response.getStatusLine() .getStatusCode() || HttpStatus.SC_CREATED == response .getStatusLine().getStatusCode())) { HttpEntity httpEntity = response.getEntity(); result = EntityUtils.toString(httpEntity);
// do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(httpEntity); } else { logger.error("Failed to invoke with post json request: " + url + ",StatusLine=" + response.getStatusLine()); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(response); } return result; }
public static boolean postJsonSuccss(String url, List<Header> headers, String json) { if (StringUtils.isEmpty(url) || StringUtils.isEmpty(json)) { return false; } CloseableHttpResponse response = null; try { HttpPost post = new HttpPost(url);
if (headers != null && !headers.isEmpty()) { for (Header header : headers) { post.addHeader(header); } }
StringEntity entity = new StringEntity(json.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity);
response = httpClient.execute(post);
if (null != response.getStatusLine() && (HttpStatus.SC_OK == response.getStatusLine() .getStatusCode() || HttpStatus.SC_CREATED == response .getStatusLine().getStatusCode())) { return true;
} else { logger.error("Failed to invoke with post json request: " + url + ",StatusLine=" + response.getStatusLine()); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(response); } return false; }
public static String get(String url) {
return request(new HttpGet(url), null, null); }
public static void main(String[] args) {
System.out.println(get("http://www.baidu.com/?wd=beibei")); }}

相关文章

    暂无相关文章
相关栏目:

用户点评