import java.io.IOException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; /**
*
*/
public class HttpClientUtil { public static void main(String arg[]) throws Exception {
String url = "test.com";
JSONObject params = new JSONObject();
params.put("SRC_STM_CODE", "wsf");
params.put("TENANT_ID", "123");
params.put("NM", "张三");
params.put("BRTH_DT", "1983-01-20");
params.put("GND_CODE", "1");
JSONArray params2 = new JSONArray();
JSONObject param3 = new JSONObject();
param3.put("DOC_TP_CODE", "10100");
param3.put("DOC_NBR", "100200198301202210");
param3.put("DOC_CUST_NM", "test");
params2.add(param3);
params.put("DOCS", params2);
String ret = doPost(url, params).toString();
System.out.println(ret);
} /**
httpClient的get请求方式2
* @return
* @throws Exception
*/
public static String doGet(String url, String charset)
throws Exception {
/*
* 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。
* 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get
* 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。
*/
/* 1 生成 HttpClinet 对象并设置参数 */
HttpClient httpClient = new HttpClient();
// 设置 Http 连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/* 2 生成 GetMethod 对象并设置参数 */
GetMethod getMethod = new GetMethod(url);
// 设置 get 请求超时为 5 秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/* 3 执行 HTTP GET 请求 */
try {
int statusCode = httpClient.executeMethod(getMethod);
/* 4 判断访问的状态码 */
if (statusCode != HttpStatus.SC_OK) {
System.err.println("请求出错: "+ getMethod.getStatusLine());
}
/* 5 处理 HTTP 响应内容 */
// HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
for (Header h : headers)
System.out.println(h.getName() + "------------ " + h.getValue());
// 读取 HTTP 响应内容,这里简单打印网页内容
byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
response = new String(responseBody, charset);
System.out.println("----------response:" + response);
// 读取为 InputStream,在网页内容数据量大时候推荐使用
// InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
System.out.println("发生网络异常!");
e.printStackTrace();
} finally {
/* 6 .释放连接 */
getMethod.releaseConnection();
}
return response;
} /**
* post请求
* @param url
* @param json
* @return
*/ public static JSONObject doPost(String url,JSONObject json){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
} }

HttpClient模拟get,post请求并发送请求参数(json等)的更多相关文章

  1. Android入门:用HttpClient模拟HTTP的GET和POST请求

    一.HttpClient介绍   HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器:   Android已经集成了HttpClient,因此可以直接使用: ...

  2. 用HttpClient模拟HTTP的GET和POST请求(转)

    本文转自:http://blog.csdn.net/xiazdong/article/details/7724349 一.HttpClient介绍   HttpClient是用来模拟HTTP请求的,其 ...

  3. .Net HttpClient 模拟登录微信公众平台发送消息

    1.模拟登录 public WeiXinRetInfo ExecLogin(string name, string pass) { CookieContainer cc = new CookieCon ...

  4. 20200726_java爬虫_使用HttpClient模拟浏览器发送请求

    浏览器获取数据: 打开浏览器 ==> 输入网址 ==> 回车查询 ==> 返回结果 ==> 浏览器显示结果数据 HttpClient获取数据: 创建HttpClient ==& ...

  5. HttpClient模拟http请求

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  6. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  7. 使用HttpClient发送请求接收响应

    1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...

  8. HTTPClient模拟Get和Post请求

    一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...

  9. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

随机推荐

  1. 如何在无法直接用VS启动代码时如何调试代码

    1. 普通情况下对进程Attach就可以调试. 2. 但是在一些情况下直接attach并无法调试,例如安装程序installer, 这样使用如下的调试方法即可调试安装程序. System.Diagno ...

  2. Ansible 变量

    1. 变量来源 inventoryfile中定义 playbook中定义 include文件和角色中定义变量 系统facts  ansible hostname -m setup local fact ...

  3. String to Double出现误差

    场景描述 做实际项目的时候,由于使用Double类的valueOf得到一个用String类型保存的金额参数(单位为元),当需要转换成以分为单位即整形表示(Integer类表示)时,需要用之前得到的do ...

  4. 10s后自动跳转

    <div class="jf_register"> <h2>您好,欢迎光临<fmt:message key="b2cShowName&quo ...

  5. ngrok内网穿透神器

    ngrok类似国内的花生壳,可以将本地的内网映射到公网上,这样就可以做web开发,微信开发了.下面就介绍下ngrok是怎么配置的吧. 方式一: 一.打开ngrok的官网https://ngrok.co ...

  6. Design Pattern - Strategy

    Strategy Pattern:     The Strategy Pattern defines a family of algorithms,encapsulates each one,and ...

  7. MyBatis-防止Sql注入以及sql中#{}与${}取参数的区别

    #{}能够更安全的取出参数 ${}取出的参数不安全 尽量不要使用${}取参数 原因: A:select * from table where a = '10001' and b = ${paramet ...

  8. es6--(三)set和map数据结构

    1.Set和WeakSet Set与数组相似,但是Set结构的成员必须是唯一的. WeakSet与对象类型,但是WeakSet结构的成员只能是对象 Set结构的实例属性和方法 属性: Set.prot ...

  9. JavaScript DOM编程艺术-学习笔记(第七章)

    第七章: 1.dom方法创建并且插入标签:(这种方法并没有改变文档的物理内容,而是在改变dom树) ①创建元素节点:createElement(); ②内部前插入:appendChild() ③创建文 ...

  10. Mr.Jobs

    Mr.Jobs   by xue 最近的情绪很down,情商智商一直往下降 主要的原因是工作不好找.不是我的要求太高, 而是公司的HR都很不要. 当然首先得自我检讨,但是,damn,这种事情我怎么做的 ...