HttpClient 4 使用方法的几个例子(代理,StringEntity字符串数据,文件上传)(转载)

1,HttpClient读取页面的使用例子:

package com.laozizhu.apache.httpclient;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;

public class HttpGet {
  public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.java2000.net", 80);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "/", "/help.jsp" };
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
        Header[] hs = response.getAllHeaders();
        for (Header h : hs) {
          System.out.println(h.getName() + ":" + h.getValue());
        }
        // 输出主体信息
        System.out.println(EntityUtils.toString(response.getEntity()));
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }
}

2 ,HttpClient 4.0通过代理访问Https的代码例子:

  

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpsProxyGet {
  public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // 认证的数据
    // 我这里是瞎写的,请根据实际情况填写
    httpclient.getCredentialsProvider().setCredentials(new AuthScope("10.60.8.20", 8080),
        new UsernamePasswordCredentials("username", "password"));
    // 访问的目标站点,端口和协议
    HttpHost targetHost = new HttpHost("www.google.com", 443, "https");
    // 代理的设置
    HttpHost proxy = new HttpHost("10.60.8.20", 8080);
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    // 目标地址
    HttpGet httpget = new HttpGet("/adsense/login/zh_CN/?");
    System.out.println("目标: " + targetHost);
    System.out.println("请求: " + httpget.getRequestLine());
    System.out.println("代理: " + proxy);
    // 执行
    HttpResponse response = httpclient.execute(targetHost, httpget);
    HttpEntity entity = response.getEntity();
    System.out.println("----------------------------------------");
    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();
    }
  }
}

3,HttpClient使用GET方式通过代理服务器读取页面的例子:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientGet {
  public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // 访问的目标站点,端口和协议
    HttpHost targetHost = new HttpHost("www.java2000.net");
    // 代理的设置
    HttpHost proxy = new HttpHost("10.60.8.20", 8080);
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    // 目标地址
    HttpGet httpget = new HttpGet("/");
    System.out.println("目标: " + targetHost);
    System.out.println("请求: " + httpget.getRequestLine());
    // 执行
    HttpResponse response = httpclient.execute(targetHost, httpget);
    HttpEntity entity = response.getEntity();
    System.out.println("----------------------------------------");
    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();
    }
  }
}

4,HttpClient 4 使用POST方式提交普通表单数据的例子:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientPost {
  public static void main(String[] args) 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://www.java2000.net/login.jsp");
    System.out.println("请求: " + httppost.getRequestLine());
    // 构造最简单的字符串数据
    StringEntity reqEntity = new StringEntity("username=test&password=test");
    // 设置类型
    reqEntity.setContentType("application/x-www-form-urlencoded");
    // 设置请求的数据
    httppost.setEntity(reqEntity);
    // 执行
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    System.out.println("----------------------------------------");
    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();
    }
  }
}

5,HttpClient 4处理文件上传的例子(MultipartEntity):

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientMultipartFormPost {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost");
    // 一个本地的文件
    FileBody bin = new FileBody(new File("d:/BIMG1181.JPG"));
    // 一个字符串
    StringBody comment = new StringBody("A binary file of some kind");
    // 多部分的实体
    MultipartEntity reqEntity = new MultipartEntity();
    // 增加
    reqEntity.addPart("bin", bin);
    reqEntity.addPart("comment", comment);
    // 设置
    httppost.setEntity(reqEntity);
    System.out.println("执行: " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println("返回长度: " + resEntity.getContentLength());
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }
  }
}

6,httpclient中文乱码解决:

httpclient默认使用ISO-8859-1读取http响应的内容,如果内容中包含汉字的话就得动用丑陋的new String(str.getBytes("ISO-8859-1"),"GBK");语句了。

解决办法就是使用以下配置。

private static final String CONTENT_CHARSET = "GBK";// httpclient读取内容时使用的字符集
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET)
时间: 2024-11-05 18:48:16

HttpClient 4 使用方法的几个例子(代理,StringEntity字符串数据,文件上传)(转载)的相关文章

Android开发之网络请求通信专题(二):基于HttpClient的文件上传下载

上一篇专题Android开发之网络请求通信专题(一):基于HttpURLConnection的请求通信我们讲解了如何使用httpurlconnection来实现基本的文本数据传输.一般在实际开发中我们可以用于传输xml或者json格式的数据.今天我们来讲解另外一种http网络请求的方式:httpclient,并实现文件的上传和下载. 在这里插个题外话,其实这些网络请求有很多第三方jar包可以使用,这些包都封装得很好了.如果只是想使用,我们就直接拿别人得jar包来用就好.博主这里推荐一个叫xuti

HttpClient构造文件上传

在项目中我们有时候需要使用到其他第三方的api,而有些api要求我们上传文件,search一下,下面将结果记录一下喽! 含义 ENCTYPE="multipart/form-data" 说明: 通过 http 协议上传文件 rfc1867协议概述,jsp 应用举例,客户端发送内容构造 1.概述在最初的 http 协议中,没有上传文件方面的功能. rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) 为 http 协议添加了这个功能.客户端的浏览器,

转 使用 HttpClient 4 进行文件上传

http://www.tuicool.com/articles/Y7reYb 1. 概述 本教程我们将描述如何使用 HttpClient 4进行一次多文件上传操作 . 我们将使用  http://echo.200please.com  作为测试服务器,因为它是面向公众的,并且接受大多数类型的内容. 如果你想要深入学习并了解你可以使用  HttpClient 做到的其它很棒的事情  – 那就去看看 首要的 HttpClient 教程吧   . 2. 使用  AddPart  方法 让我们开始研究研

selenium之 文件上传所有方法整理总结

本文转载"灰蓝"的原创博客.http://blog.csdn.net/huilan_same/article/details/52439546 文件上传是所有UI自动化测试都要面对的一个头疼问题,今天博主在这里给大家分享下自己处理文件上传的经验,希望能够帮助到广大被文件上传坑住的seleniumer. 首先,我们要区分出上传按钮的种类,大体上可以分为两种,一种是input框,另外一种就比较复杂,通过js.flash等实现,标签非input 我们分别对这两种进行分析: 1.input标签

ASP中文件上传组件ASPUpload介绍和使用方法

[导读]要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件 1 下载和安装ASPUpload  要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件,它的下载网址是:           http://www.persits.com/aspupload.exe       组件提供者网址是:           http://www.aspupload.com    

04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

 1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mvc结构 DispatcherServlet:中央控制器,把请求给转发到具体的控制类 Controller:具体处理请求的控制器(配置文件方式需要配置,注解方式不用配置) handlerMapping:映射处理器,负责映射中央处理器转发给controller时的映射策略 ModelAndView:服务

spring mvc文件上传方法

spring mvc上传功能很强大. spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype="multipart/form-data" 这个是上传文件必须的2.applicationContext.xml中 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolv

Android使用HttpClient实现文件上传到PHP服务器,并监控进度条

上传 服务器端PHP 代码如下 : <?php $target_path = "./tmp/";//接收文件目录 $target_path = $target_path.($_FILES['file']['name']); $target_path = iconv("UTF-8","gb2312", $target_path); if(move_uploaded_file($_FILES['file']['tmp_name'], $targ

java 文件上传例子

现在要处理一些CSV格式的数据,就想着把文件上载到服务器上,然后导入mysql,再做后续的处理. 用到了JKD1.7,Servlet 3.0 和 tomcat 7.0.由于Servlet 3.0直接支持文件上传,直接调用方法就好了. 还有一个官方的教程. http://docs.oracle.com/javaee/7/tutorial/doc/servlets016.htm#BABDGFJJ. 按着这个做基本就可以了,但是有两点需要注意: 1 我用的IDE是eclipse,eclipse在运行的