一、前言
通过apache的DefaultHttpClient(htmlunit-2.8.jar)模拟浏览器终端模拟访问请求HttpResponse - 下面分别基于org.apache.http.client.methods.HttpPost、org.apache.http.client.methods.HttpGet实现以POST、GET请求方式访问获取数据,其中org.apache.http.message.BasicNameValuePair注入入参序列List <NameValuePair>到HttpPost对象中,详细参见下面示例代码。
二、示例说明
package test;@b@import java.util.ArrayList;@b@import java.util.List;@b@import org.apache.http.HttpEntity;@b@import org.apache.http.HttpResponse;@b@import org.apache.http.NameValuePair;@b@import org.apache.http.client.entity.UrlEncodedFormEntity;@b@import org.apache.http.client.methods.HttpGet;@b@import org.apache.http.client.methods.HttpPost;@b@import org.apache.http.impl.client.DefaultHttpClient;@b@import org.apache.http.message.BasicNameValuePair;@b@import org.apache.http.protocol.HTTP;@b@import org.apache.http.util.EntityUtils;@b@@b@public class HttpClientDemo {@b@@b@ public static String doPost() { @b@ String result = ""; @b@ HttpPost post = new HttpPost("http://127.0.0.1/api/order");@b@ List <NameValuePair> params = new ArrayList<NameValuePair>(); @b@ params.add(new BasicNameValuePair("userName", "nijun")); @b@ params.add(new BasicNameValuePair("productId", "12345")); @b@ try { @b@ post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); @b@ HttpResponse response = new DefaultHttpClient().execute(post); @b@ if(response.getStatusLine().getStatusCode() == 200){ @b@ HttpEntity responseEntity = response.getEntity(); @b@ result = EntityUtils.toString(responseEntity);@b@ } @b@ } catch (Exception e) { } @b@ return result; @b@ } @b@ @b@ @b@ public static String doGet(){ @b@ String result= ""; @b@ HttpGet get = new HttpGet("http://127.0.0.1/api/order?userName=nijun&productId=12345"); @b@ try{ @b@ HttpResponse response = new DefaultHttpClient().execute(get);@b@ if(response.getStatusLine().getStatusCode() == 200){ @b@ HttpEntity responseEntity = response.getEntity(); @b@ result = EntityUtils.toString(responseEntity);@b@ result.replaceAll("\r", "");@b@ } @b@ }catch (Exception e) { } @b@ return result; @b@ } @b@@b@ @b@@b@ public static void main(String[] args) throws Exception{@b@ String result = doPost();@b@// String result = doGet();@b@ System.out.println(result);@b@ }@b@@b@}