您的位置:首页 > 理论基础 > 计算机网络

HTTP请求

2016-08-03 00:00 134 查看
摘要: HTTP请求

##HTTP请求##

HttpClientHelp

package com.ice.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class HttpClientHelp {

// 创建默认的httpClient客户端
private HttpClient httpClient = null;

// get模式
private HttpGet httpGet = null;

// post模式
private HttpPost httpPost = null;

// 执行请求,获取服务器响应
private HttpResponse response = null;

// 请求的实体
private HttpEntity entity = null;

// 输入流
private InputStream is = null;

/**
* 释放资源
* [@param](http://my.oschina.net/u/2303379) httpGet
* [@param](http://my.oschina.net/u/2303379) httpPost
* [@param](http://my.oschina.net/u/2303379) httpClient
*/
public void releaseSource(HttpGet httpGet,
HttpPost httpPost, HttpClient httpClient) {
if (httpGet != null) {
httpGet.abort();
}
if (httpPost != null) {
httpPost.abort();
}
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}

/**
* get方式提交并返回InputStream
* [@param](http://my.oschina.net/u/2303379) url 提交的url
* [@param](http://my.oschina.net/u/2303379) client HttpClient
* @param get HttpGet
* @return
*/
public InputStream byGetMethod(HttpClient client,HttpGet get) {
try {
// 执行请求
response = client.execute(get);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
// 将entity返回InputStream
is = entity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return is;
}

/**
* @MethodName: byGetMethodToInputStream
* @Param: HttpClientHelp
* @Author: gang.lv
* @Date: 2013-4-6 下午08:20:05
* @Return:
* @Descb: 提交返回流
* @Throws:
*/
public InputStream byGetMethodToInputStream(String url){
StringBuffer buff = new StringBuffer();
// 创建线程安全的httpClient
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
// 创建一个HttpGet请求,作为目标地址。
httpGet = new HttpGet(url);

try {
response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
is = entity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
releaseSource(httpGet, null, httpClient);
}
return is;
}
/**
* get方式提交并且返回Entity字符串
* @param url 提交的url
* @return
*/
public String byGetMethodToHttpEntity(String url) {
StringBuffer buff = new StringBuffer();
// 创建线程安全的httpClient
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
// 创建一个HttpGet请求,作为目标地址。
httpGet = new HttpGet(url);

try {
response = httpClient.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
buff.append(EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
releaseSource(httpGet, null, httpClient);
}
return buff.toString();
}

/**
* Post方式提交并且返回InputStream
* @param url 提交的url
* @param client HttpClient
* @param post  HttpPost
* @param params 队列参数
* @param urlEncoded  url编码
* @return
*/
public InputStream byPostMethod(HttpClient client,HttpPost post, List<NameValuePair> params,String urlEncoded) {
try {
if(params != null){
// 格式化参数列表并提交
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params,
urlEncoded);
response.setEntity(uefEntity);
}
response = client.execute(post);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
// 将entity返回InputStream
is = entity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return is;
}

/**
* Post方式提交并且返回Entity字符串
* @param url 提交的url
* @param client HttpClient
* @param post  HttpPost
* @param params 队列参数
* @param urlEncoded  url编码
* @return
*/
public String byPostMethodToHttpEntity(String url,
List<NameValuePair> params,String urlEncoded) {
StringBuffer buff = new StringBuffer();
// 创建线程安全的httpClient
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
// 创建一个HttpGet请求,作为目标地址。
httpPost = new HttpPost(url);
try {
if(params != null){
// 格式化参数列表并提交
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params,
urlEncoded);
httpPost.setEntity(uefEntity);
}
response = httpClient.execute(httpPost);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
buff.append(EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
releaseSource(null, httpPost, httpClient);
}
return buff.toString();
}

/**
* @ClassName: byPostMethodToHttpEntity
* @Description:
* @author win
* @date 2015-9-28 下午02:33:22
*/
public String byPostMethodToHttpEntity(String url,
String params,String urlEncoded) {
StringBuffer buff = new StringBuffer();
// 创建线程安全的httpClient
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
// 创建一个HttpGet请求,作为目标地址。
httpPost = new HttpPost(url);
try {
if(params != null){
StringEntity uefEntity = new StringEntity(params, "UTF-8");
httpPost.setEntity(uefEntity);
}
response = httpClient.execute(httpPost);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
entity = response.getEntity();
buff.append(EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
releaseSource(null, httpPost, httpClient);
}
return buff.toString();
}

}


HttpUtil工具类

package com.ice.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* http请求工具类
*/
public class HttpUtil {
private static Log log = LogFactory.getLog(FormUtil.class);

/**
* 发送请求 ,返回请求结果
*/
public static String http(String url, Map<String, String> params) {
URL u = null;
HttpURLConnection con = null;
// 构建请求参数
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Entry<String, String> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append("&");
log.info(e.getKey() + "=============" + e.getValue());
}
sb.deleteCharAt(sb.length() - 1);
}
// 发送请求
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}

// 读取返回内容
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
JSONObject json = null;
try {
json = JSONObject.fromObject(buffer.toString());
} catch (Exception e) {
json = new JSONObject();
json.put("RespCode", 3838);
String str = buffer.toString();
try {
int index = 0;
if(str.contains("<p class=\"title\">")){
str = str.substring(str.indexOf("<p class=\"title\">")+17);
index = str.indexOf("</p>");
str = str.substring(0, index);
}else if (str.contains("<p class=\"desc\">")){
str = str.substring(str.indexOf("<p class=\"desc\">") + 17);
index = str.indexOf("</p>");
str = str.substring(0, index);
}
} catch (Exception ee) {
str = "未知异常";
}
json.put("RespDesc", "汇付返回结果:"+str);
}
return json.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HTTP请求