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

httpclient调用struts服务

2018-01-16 15:44 543 查看
package com;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.http.NameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
*
*
* @author muyunfei
*
* <p>Modification History:</p>
* <p>Date       Author      Description</p>
* <p>------------------------------------------------------------------</p>
* <p>Oct 9, 2016           牟云飞       		 新建</p>
*/
public class BugMain {
public static void main(String[] args) {
try{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost= new HttpPost("http://www.XXXXXX.com/XXXXXX/serviceInvoke.do");
httpPost.setHeader("hy_serviceName", "chargeXXXXX");
httpPost.setHeader("account", "1556257XXXXX");
httpPost.setHeader("password ", "mima");
httpPost.setHeader("signature ", "dX5db5tnj1gQt0c7TkmB1A==");
httpPost.setHeader("timeStr ", "1499134848000");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("channel", "0"));
params.add(new BasicNameValuePair("chargeId", "FS-Z-002"));//充电枪
params.add(new BasicNameValuePair("chargeNumber", "0"));//充满电
params.add(new BasicNameValuePair("chargeType", "4"));//充满电
params.add(new BasicNameValuePair("pointId", "0"));//充电枪号
params.add(new BasicNameValuePair("type", "0"));
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
// Create a custom response handler
ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
//成功调用连接后,对返回数据进行的操作
public JSONObject handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
//获得调用成功后  返回的数据
HttpEntity entity = response.getEntity();
if(null!=entity){
String result= EntityUtils.toString(entity);
//根据字符串生成JSON对象
JSONObject resultObj = JSONObject.fromObject(result);
return resultObj;
}else{
return null;
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}

};
//返回的json对象
JSONObject responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println(responseBody);
}catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: