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

通过http请求服务

2014-07-25 16:45 218 查看
package com.base.utils;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.Header;

import org.apache.http.HttpResponse;

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.client.params.HttpClientParams;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicHeader;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.apache.http.params.HttpProtocolParams;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil {

private static HttpParams httpParams;

private static HttpClient httpClient;

static{

httpClient=getHttpClient();

}

public static String doPost(String url, Map<String, String> paramsMap,Map<String, String> headers) {

/* 建立HTTPPost对象 */

HttpPost httpRequest = new HttpPost(url);

String strResult = "doPostError";

try {

/*封装参数*/

List<NameValuePair> params = new ArrayList<NameValuePair>();

/* params.add(new BasicNameValuePair("openId", Constants.OPEN_ID));

params.add(new BasicNameValuePair("openKey", Constants.OPEN_KEY));*/

if (paramsMap != null) {

for (String str : paramsMap.keySet()) {

params.add(new BasicNameValuePair(str, paramsMap.get(str)));

}

}

/* 添加请求参数到请求对象 */

httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

/* 发送请求并等待响应 */

if (headers != null) {

httpRequest.setHeaders(assembHead(headers));

}

HttpResponse httpResponse = httpClient.execute(httpRequest);

/* 若状态码为200 ok */

if (httpResponse.getStatusLine().getStatusCode() == 200) {

/* 读返回数据 */

strResult = EntityUtils.toString(httpResponse.getEntity());

} else {

//Log.e("net_error", httpResponse.getStatusLine().toString());

JSONObject retObj=new JSONObject();

retObj.put("success", false);

retObj.put("wserror", true);

retObj.put("message", httpResponse.getStatusLine().toString());

strResult = retObj.toJSONString();

}

} catch (ClientProtocolException e) {

//Log.e("net_error", e.getMessage().toString());

JSONObject retObj=new JSONObject();

retObj.put("success", false);

retObj.put("wserror", true);

retObj.put("message", e.getMessage().toString());

strResult = retObj.toJSONString();

} catch (IOException e) {

//Log.e("net_error", e.getMessage().toString());

JSONObject retObj=new JSONObject();

retObj.put("success", false);

retObj.put("wserror", true);

retObj.put("message", e.getMessage().toString());

strResult = retObj.toJSONString();

} catch (Exception e) {

//Log.e("net_error", e.getMessage().toString());

JSONObject retObj=new JSONObject();

retObj.put("success", false);

retObj.put("wserror", true);

retObj.put("message", e.getMessage().toString());

strResult = retObj.toJSONString();

}

return strResult;

}

public static String doGet(String url, Map<String, String> headers)

throws ClientProtocolException, IOException {

// DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient();

HttpGet httpGet = new HttpGet(url);

String strResult = "";

if (headers != null) {

httpGet.setHeaders(assembHead(headers));

}

HttpResponse httpResponse = httpClient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {

strResult = EntityUtils.toString(httpResponse.getEntity());

}

httpGet.abort();

return strResult;

}

public static Header[] assembHead(Map<String, String> headers) {

Header[] allHeader = new BasicHeader[headers.size()];

int i = 0;

for (String str : headers.keySet()) {

allHeader[i] = new BasicHeader(str, headers.get(str));

i++;

}

return allHeader;

}

public static HttpClient getHttpClient() {

// 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)

httpParams = new BasicHttpParams();

// 设置连接超时和 Socket 超时,以及 Socket 缓存大小

HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

// 设置重定向,缺省为 true

HttpClientParams.setRedirecting(httpParams, true);

// 设置 user agent

String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";

HttpProtocolParams.setUserAgent(httpParams, userAgent);

// 创建一个 HttpClient 实例

// 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient

// 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient

httpClient = new DefaultHttpClient(httpParams);

return httpClient;

}

}

调用:

Map<String, String> param=new HashMap<String, String>();

param.put("TableName", "drug_remind");

param.put("SelectColumns", "sn,medname,repeat,times,begindate,enddate");

param.put("WhereColumns", "[{\"Column\":\"sn\",\"Type\":\"str\",\"Sign\":\"=\",\"Value\":\"0500302955006\"}]");

String res=HttpClientUtil.doPost("http://ccapi.zgjkw.cn/bsoft.svc/QueryTable", param, null);

System.out.println(res);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: