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

java httpRequest协议请求分享

2015-08-13 17:20 447 查看
import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

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

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

public class HttpTest {

public static void main(String args[]){

String uriAPI = "http://localhost:8080/mgc/ws/terminal/spcharge/spChargeRollBack";

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

map.put("err_msg", "123");

map.put("p", "345");

test(uriAPI,map);

}

public static String test(String url, Map<String, String> a){

/*建立HTTPost对象 */

HttpPost httpRequest = new HttpPost(url);

/*

* NameValuePair实现请求参数的封装

*/

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

for(Entry<String,String> i: a.entrySet()){

params.add(new BasicNameValuePair(i.getKey(), i.getValue()));

}

try {

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

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

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

HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

/* 若状态码为200 ok */

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

/* 读返回数据 */

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

System.out.println("HHHHHH:"+strResult);

return strResult;

} else {

return ("Error Response: " + httpResponse.getStatusLine().toString());

}

} catch (ClientProtocolException e) {

return (e.getMessage().toString());

} catch (IOException e) {

return (e.getMessage().toString());

} catch (Exception e) {

return (e.getMessage().toString());

}

}

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