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");
//------------
//也可以用使用StringEntity,
//但是需要增加
//httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//UrlEncodedFormEntity 是StringEntity的封装
//------------
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();
}
}
}
httpclient调用struts服务
于 2018-01-16 15:44:53 首次发布