httpclient4 发送http请求的get和post用法
2013-11-11 16:54
253 查看
package http; public class BasicParameter { private String name; private String value; public BasicParameter(String name,String value){ this.name = name; this.value = value; } public String getName(){ return this.name; } public String getValue(){ return this.value; } }
package http; import java.io.File; import java.util.ArrayList; import java.util.List; public class HttpParameter { private final List<BasicParameter> parameter =new ArrayList<BasicParameter>(); private final List<FileParameter> fileparameter = new ArrayList<FileParameter>(0); //存放name,value形式的Basicparameter类型的对象,将对象存入parameter集合 public void add(String name,String value){ this.parameter.add(new BasicParameter(name,value));} public void addfile(String name,File file){ this.fileparameter.add(new FileParameter(name,file)); } public List<BasicParameter> getBasicParameters(){ return parameter; } public List<FileParameter> getFileParameter(){ return fileparameter; } public boolean isBasicParameterEmpty(){ return this.parameter.isEmpty(); } public boolean isFileParameterEmpty(){ return this.fileparameter.isEmpty(); } public boolean isAllParameterEmpty(){ return this.parameter.isEmpty() &&this.fileparameter.isEmpty(); } }
package http; import java.io.UnsupportedEncodingException; public class HttpResp { private int statusCode; //创建字节数组,将返回的实体内容放在这里面 private byte[] bytes; private String text; public int getStatusCode(){ return this.statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getText(String charset){ if(text == null){ try { //将bytes转化为utf-8字符编码 text = new String(bytes,charset); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return text; } public byte[] getBytes(){ return this.bytes; } public void setBytes(byte[] bytes){ this.bytes = bytes; } }
package http; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.HttpEntity; 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.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; public class HttpClient4 { private HttpClient httpclient; public static HttpClient4 createDefault(){ return new HttpClient4(); } public HttpClient4(int timeout){ //HttpClient 是接口,DefaultHttpClient是实现这个接口的子类 httpclient = new DefaultHttpClient(); //读取超时 httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); //HttpHost proxy = new HttpHost("someproxy", 8080); //httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } public HttpClient4(){ this(3000); } public void setHttpClient(HttpClient httpclient){ this.httpclient = httpclient; } public HttpClient getHttpClient(){ return this.httpclient; } /** * get请求 * @param url * @param httpParameter * @param charset * @return HttpResp * @throws ClientProtocolException * @throws IOException * * */ public HttpResp doGet(String url, HttpParameter httpParameter, String charset) throws ClientProtocolException, IOException { StringBuilder sb = new StringBuilder(url); if (httpParameter != null && !httpParameter.isAllParameterEmpty()) { //返回 String 对象内第一次出现子字符串的字符位置 //ndexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。 if (url.indexOf("?") ==-1){ sb.append("?"); } if (!url.endsWith("?")){ sb.append("&"); } for (BasicParameter o:httpParameter.getBasicParameters()) { //url中的中文参数经行编码的,可以解决乱码的问题 sb.append(URLEncoder.encode(o.getName(), charset)); sb.append("="); sb.append(URLEncoder.encode(o.getValue(), charset)); sb.append("&"); } //是删除某个位置的单个字符 if (sb.length()>0) { sb.deleteCharAt(sb.length()-1); } } HttpGet httpget = new HttpGet(sb.toString()); return this.execute(httpget); } /** * post请求 * @param url * @param httpParameter * @param charset * @return HttpResp * @throws ClientProtocolException * @throws IOException * * */ public HttpResp doPost(String url, HttpParameter httpParameter, String charset) throws ClientProtocolException, IOException { HttpPost httpPost = new HttpPost(url); // if (httpParameter.isFileParameterEmpty()) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (BasicParameter e : httpParameter.getBasicParameters()) { nameValuePairs.add(new BasicNameValuePair(e.getName(), e .getValue())); // } ///* 添加请求参数到请求对象*/ httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset)); // } // else { // MultipartEntity reqEntity = new MultipartEntity(); // for (FileParameter e : httpParameter.getFileParameter()) { // reqEntity.addPart(e.getName(), new FileBody(e.getFile())); // } // for (BasicParameter e : httpParameter.getBasicParameters()) { // reqEntity.addPart(e.getName(), new StringBody(e.getValue(), // Charset.forName(charset))); // } // httpPost.setEntity(reqEntity); } return this.execute(httpPost); } private HttpResp execute(HttpRequestBase request) throws ClientProtocolException, IOException { HttpEntity entity = null; try { //执行请求连接 HttpResponse httpResponse = httpclient.execute(request); //返回类的对象,调用setstatuscode方法 HttpResp httpResp = new HttpResp(); //得到返回的状态码,传递给httpresp类的状态码进行输出 httpResp.setStatusCode(httpResponse.getStatusLine().getStatusCode()); //得到实体 entity = httpResponse.getEntity(); //将实体内容转化为字节数组 httpResp.setBytes(EntityUtils.toByteArray(entity)); return httpResp; } catch (ClientProtocolException e) { // 协议错误 throw e; } catch (IOException e) { //网络错误 throw e; } finally { if (entity != null) { EntityUtils.consume(entity); } } } /** * 最终可释放资源调用 */ //DefaultHttpClient是线程安全的。建议相同的这个类的实例被重用于多个请求的执行。 //当一个DefaultHttpClient实例不再需要而且要脱离范围时, //和它关联的连接管理器必须调用ClientConnectionManager#shutdown()方法关闭。 public void shutdown() { this.httpclient.getConnectionManager().shutdown(); } public void executeMethod(PostMethod method) { // TODO Auto-generated method stub } }
调用接口
public void testxxxx(){ //参数 Random rd = new Random(); int s=rd.nextInt(); String order_id=""+s; //get请求 String url = "http://xxxxxx/xxxp/xxxxxx"; HttpClient4 client =HttpClient4.createDefault(); HttpParameter parameter = new HttpParameter(); parameter.add("xxxx","xx"); parameter.add("xxxx", xxxx); HttpResp rep; try { rep = client.doGet(url, parameter,"utf-8"); System.out.println(rep.getText("utf-8")); }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } post同理,只需要把doGet改为dopost即可
相关文章推荐
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- (三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- (三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- android内置的HttpClient发送get、post请求用法
- HttpClient发送get请求,post请求,携带cookie访问,json提交
- java apache commons HttpClient发送get和post请求的学习整理
- 我的Android进阶之旅------>Android发送GET和POST以及HttpClient发送POST请求给服务器响应
- HttpClient发送get和post工具类
- java apache commons HttpClient发送get和post请求的学习整理
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
- java apache commons HttpClient发送get和post请求的学习整理
- HttpClient的用法(包含httpget和httppost)
- HttpClient发送GET Post例子4.2.1版本