`

DefaultHttpClient使用

阅读更多

 

  1 httpClient封装后使用,get和post方法

package util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * @Title:TestHttpClient
 * @Author Tony
 * @Date: 2014年6月21日 下午3:29:37
 * @Description:  httpClient使用,1 发送post请求   2 发送get请求 
 * 
 */
public class TestHttpClient {

 
	/**
	* @Title: methodPost 
	* @Description: httpclient方法中post提交数据的使用 
	* @param @return
	* @param @throws Exception   
	* @return String    
	* @throws
	 */
	public static String methodPost() throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// // 代理的设置
		// HttpHost proxy = new HttpHost("10.60.8.20", 8080);
		// httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		// proxy);

		// 目标地址
		HttpPost httppost = new HttpPost(
				"http://localhost:8011/testServlet");
		System.out.println("请求: " + httppost.getRequestLine());
 
		// post 参数 传递
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		nvps.add(new BasicNameValuePair("content", "11111111")); // 参数
		nvps.add(new BasicNameValuePair("path", "D:/file")); // 参数
		nvps.add(new BasicNameValuePair("name", "8")); // 参数
		nvps.add(new BasicNameValuePair("age", "9")); // 参数
		nvps.add(new BasicNameValuePair("username", "wzt")); // 参数

		httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // 设置参数给Post

		// 执行
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		System.out.println(response.getStatusLine());
		if (entity != null) {
			System.out.println("Response content length: "
					+ entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				entity.getContent(), "UTF-8"));

		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		if (entity != null) {
			entity.consumeContent();
		}
		return null;

	}
	
	/**
	* @Title: methodGet 
	* @Description:  以get方法提交数的使用 
	* @param @return
	* @param @throws Exception   
	* @return String    
	* @throws
	 */
	public static  String methodGet() throws  Exception { 
		   DefaultHttpClient httpclient = new DefaultHttpClient();   
//			     // 代理的设置   
//			      HttpHost proxy = new HttpHost("10.60.8.20", 8080);   
//			      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);   


		    // 目标地址   
		     HttpPost httpGet = new HttpPost("http://localhost:8011/testServlet");   
		     
		     // 构造最简单的字符串数据   
		      StringEntity reqEntity = new StringEntity("name=test&password=test");   
		     // 设置类型   
		      reqEntity.setContentType("application/x-www-form-urlencoded");   
		     // 设置请求的数据   
		      httpGet.setEntity(reqEntity);   
		  
		     // 执行   
		     HttpResponse response = httpclient.execute(httpGet);   
		     HttpEntity entity = response.getEntity();   
		     System.out.println(response.getStatusLine());   
		     
		    if (entity != null) {   
		       System.out.println("Response content length: " + entity.getContentLength());  //得到返回数据的长度  
		     }   
		     // 显示结果   
		     BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); 
		     
		     String line = null;   
		    while ((line = reader.readLine()) != null) {   
		         System.out.println(line);   
		     }   
		    if (entity != null) {   
		          entity.consumeContent();   
		     }   
		    return null; 

		} 
	
	/**
	 * 模拟url访问 从特定的url中获取json
	 * 
	 * @param urlStr
	 * @param params
	 * @return json object ,or null if failed
	 * 参数经过封装后传过来 ,提交为 post请求
	 */
	private static JSONObject getJsonFromUrl(String urlStr,
			Map<String, String> params) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(urlStr);
		JSONObject json = null;
		try {
			if (params != null) {
				Iterator<String> keys = params.keySet().iterator();
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				while (keys.hasNext()) {
					String key = keys.next();
					nvps.add(new BasicNameValuePair(key, params.get(key)));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			}
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			byte[] bytes = new byte[256];
			StringBuffer sb = new StringBuffer();
			while (is.read(bytes) > 0) {
				sb.append(new String(bytes));
				bytes = new byte[256];
			}
			json = JSONObject.fromObject(sb.toString());
		} catch (Exception e) {
			 e.printStackTrace();
		}

		return json;
	}
	
	/**
	* @Title: main 
	* @Description: 测试类 
	* @param @param args   
	* @return void    
	* @throws
	 */
	public static void main(String[] args) {
		try {
			TestHttpClient.methodGet();
//			TestHttpClient.methodPost();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 2 后台接受数据的servlet 

 

public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( "utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		
		String name = request.getParameter("name");
		System.out.println("name 变量数据: "+name);
	}
}

 

 

 

 

分享到:
评论
11 楼 java_frog 2017-12-25  
httpclient4里才有default
10 楼 lizhenlzlz 2017-07-14  
lizhenlzlz 写道
HttpHost proxy = new HttpHost("ip",端口); 
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
对我有用

再次对我有用
9 楼 lizhenlzlz 2017-06-01  
HttpHost proxy = new HttpHost("ip",端口); 
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
对我有用
8 楼 kennykinte 2015-12-04  
methodGet()方法里
HttpPost httpGet = new HttpPost("http://localhost:8011/testServlet"); 

实例化的是HttpPost对象。。。。楼主是来搞笑的吗?
7 楼 孟明视 2015-09-20  
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
6 楼 孟明视 2015-09-20  
import org.apache.h没啊。这个包
5 楼 savage-qq 2014-07-16  
请问,安卓客户端不是已经集成httpClient了嘛? 为什么还需要专门用jar包?
4 楼 username2 2014-06-21  
sulong2088 写道
只有个测试方法,你能把客户端  服务端代码给我贴全吗?


今天刚看到问题,又重新整理了一下整个方法,加入了一个jar文件,服务端就是一个Servlet就可以了。
3 楼 sulong2088 2014-04-02  
只有个测试方法,你能把客户端  服务端代码给我贴全吗?
2 楼 MyJavaDisk 2013-12-03  
谢谢!谢谢,谢谢!
1 楼 MyJavaDisk 2013-12-03  
       

相关推荐

    DefaultHttpClient_httpsDemo.rar

    DefaultHttpClient绕过安全认证访 DefaultHttpClient 请求绕过 https 实例

    httpclient jar

    import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache....

    Android学习之HttpClient练习(一)

    练习HttpClient的一个Demo

    Android使用Apache的HttpClient访问微Web站点

    本实例描述了Android平台下使用Apache开源项目的HttpClient访问网络的示例。分别使用HttpClient下的两个子实现类,DefaultHttpClient和AndroidHttpClient分别进行演示。

    httpclient过时用的jar包

    httpclient过时用的jar包 , 解决项目升级后httpclient过时程序报错

    http依赖jar包.zip

    import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; 这些...

    httpClient4.5配置SSL绕过https证书,httpClient过时替代方法-附件资源

    httpClient4.5配置SSL绕过https证书,httpClient过时替代方法-附件资源

    httpclient-4.1.2.jar

    httpclient的jar包,包含DefaultHttpClient

    HttpClient相关包

    import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache....

    httpClient及android 原生接口实现下载并显示图片 源码

    《 httpClient及android 原生接口实现下载并显示图片》博客对应源码,博客地址:http://blog.csdn.net/harvic880925/article/details/17609771

    Android抓取CSDN首页极客头条内容完整实例

    今天,写了个小代码。...HttpClient httpClient = new DefaultHttpClient(); //创建一个HttpClient HttpGet httpGet = new HttpGet(“http://www.csdn.net/”); //创建一个GET请求 HttpResponse respons

    AndroidHttpClient使用Cookie应用分析

    今天想把一个用使用了HttpClient的自动签到小程序移植到Android上,还好Android的SDK自带了HttpClient的包.当然也可以继续使用DefaultHttpClient,但用为Android定制的AndroidHttpClient自然更好

    android Http Post 连接服务器超时Demo

    new Thread(new Runnable() { public void run() { // TODO Auto-generated method stub try { //设置连接超时 ... DefaultHttpClient httpclient = new DefaultHttpClient( httpParameters);

    org.apache.http源代码和jar包

    该jar包包含: import org.apache.http.Header; import org.apache.... ... ... ...import org.apache.http.impl.client.DefaultHttpClient;...可以解决Android-SDK新更新之后,使用http缺少org.apache.http的一些问题.

    org.apache.http jar包

    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;

    android HttpDemo

    android HTTPdemo,分别用HttpURLConnection类,和DefaultHttpClient类 实现了 POST、GET方法

    toon-api:用于 Eneco Toon 恒温器的逆向工程 Java API

    卡通API ... new ToonClient ( new DefaultHttpClient ()) 用法 卡通客户端 例子: // Create a toon client instance using the default ToonMemoryPersistenceHandler. // Remember that when you

    android读写cookie的方法示例

    做了一个android网络应用,要求用自己实现的webview去访问web网站,并且... DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(http://www.hlovey.com); HttpResponse respons

    HtmlEmail发送邮件+HttpClient下载功能

    //这里也可以直接使用httpGet的绝对地址,当然如果不是具体地址不要忘记/结尾 //HttpGet httpGet = new HttpGet("http://www.0431.la/"); //HttpResponse response = httpClient.execute(httpGet); ...

Global site tag (gtag.js) - Google Analytics