关于java http请求Client的问题,两个系统对接为什么接收不到信息

java发送HttpClient请求及接收请求结果过程的简单实例
投稿:jingxian
字体:[ ] 类型:转载 时间:
下面小编就为大家带来一篇java发送HttpClient请求及接收请求结果过程的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1、写一个HttpRequestUtils工具类,包括post请求和get请求
package com.brainlong.framework.util.
import net.sf.json.JSONO
import mons.httpclient.HttpS
import org.apache.http.HttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.entity.StringE
import org.apache.http.impl.client.DefaultHttpCimport org.apache.http.util.EntityU
import org.slf4j.L
import org.slf4j.LoggerF
import java.io.IOEimport java.net.URLD public class HttpRequestUtils {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
//日志记录
* httpPost
* @param url 路径
* @param jsonParam 参数
public static JSONObject httpPost(String url,JSONObject jsonParam){
return httpPost(url, jsonParam, false);
* post请求
* @param url
* @param jsonParam
* @param noNeedResponse
不需要返回结果
public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult =
HttpPost method = new HttpPost(url);
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
return jsonR
* 发送get请求
* @param url
public static JSONObject httpGet(String url){
//get请求返回结果
JSONObject jsonResult =
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(strResult);
url = URLDecoder.decode(url, "UTF-8");
logger.error("get请求提交失败:" + url);
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
return jsonR
2、写业务代码发送Http请求
3、MVC配置文件设置Controller扫描目录
&!-- 自动扫描且只扫描@Controller --&
&context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false"&
&context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /&
&/context:component-scan&
4、接收Http请求
接收post请求
@Controller
@RequestMapping(value&=&"/api/platform/exceptioncenter/exceptioninfo")
public&class&ExceptionInfoController&{
@Autowired
private&ExceptionInfoBiz&exceptionInfoB
*&创建异常信息请求
*&@param&requestBody&请求消息内容
*&@param&request&请求消息头
*&@return&jsonObject
@RequestMapping(
value="/create",
method&=&RequestMethod.POST
public&ModelAndView&createExceptionInfo(@RequestBody&String&requestBody,&HttpServletRequest&request)&{
JSONObject&jsonObject&=&JSONObject.fromObject(requestBody);
ComExceptionInfo&comExceptionInfo&=&new&ComExceptionInfo();
comExceptionInfo.setProjectName(jsonObject.getString("projectName"));
comExceptionInfo.setTagName(jsonObject.getString("tagName"));
exceptionInfoBiz.insert(comExceptionInfo);
//返回请求结果
JSONObject&result=&new&JSONObject();
result.put("success",&"true");
return&new&ModelAndView("",&ResponseUtilsHelper.jsonSuccess(result.toString()));
接收get请求
@Controller
@RequestMapping(value="/api/platform/messagecenter/messages/sms")
public&class&SmsController&{
@Autowired
SmsSendBiz&smsSendB
*&接收手机号码和内容往短信发送表插入一条记录
*&@param&requestbody&请求消息内容
*&@param&request&请求消息头
*&@return&jsonObject
@RequestMapping(
value="/send",
method=&RequestMethod.GET
public&ModelAndView&sendSms(@RequestBody&String&requestbody,&HttpServletRequest&request)&{
//获取请求URL及url后面传输的参数
String&url&=&request.getRequestURL()&+&"?"&+&request.getQueryString();
url&=&BuildRequestUrl.decodeUrl(url);
String&telePhone&=&RequestUtils.getStringValue(request,&"telePhone");
String&content&=&RequestUtils.getStringValue(request,&"content");
smsSendBiz.insertTtMsQuequ(telePhone,content);
return&new&ModelAndView("",&ResponseUtilsHelper.jsonResult("",&true));
import&java.io.BufferedR
import&java.io.IOE
import&java.io.InputS
import&java.io.InputStreamR
import&mons.httpclient.HttpC
import&mons.httpclient.HttpM
import&mons.httpclient.methods.GetM
public&class&H_client_get&{
public&static&void&main(String[]&args)&throws&IOException&{
//&new类对象
HttpClient&client&=&new&HttpClient();
//&使用&GET&方法&与URL服务器进行交互
//&HttpMethod&method&=&new&GetMethod("http://192.168.111.128/bak/regist.php?email=&password=1234567&re_password=1234567&username=admin&nickname=管理员");
HttpMethod&method&=&new&GetMethod("http://192.168.111.128/bak/login.php?username=");
//&使用&GET&方法&,实行与url服务器连接
client.executeMethod(method);
//&数据流输出
//&method.getResponseBodyAsStream&创建字节流对象为inputStream
InputStream&inputStream&=&method.getResponseBodyAsStream();
//&InputStreamReader(inputStream)字节流转换成字符流&BufferedReader封装成带有缓冲的字符流对象了&
BufferedReader&br&=&new&BufferedReader(new&InputStreamReader(inputStream,"UTF-8"));
//&StringBuffer是字符串变量,它的对象是可以扩充和修改的&创建一个空的StringBuffer类的对象&
StringBuffer&stringBuffer&=&new&StringBuffer();
//&定义字符串常量
String&str=&"";
//&br字符流赋值给str字符串常量&str不等于空&按行输出
while((str&=&br.readLine())&!=&null){&
//&StringBuffer&是字符串变量,它的对象是可以扩充和修改的&将str数据赋予&stringBuffer&
stringBuffer&.append(str&);&
//&按照字符串循环输出stringBuffer
System.out.println(stringBuffer.toString());
//&关闭method&的&httpclient连接
method.releaseConnection();
import&java.io.BufferedR
import&java.io.IOE
import&java.io.InputS
import&java.io.InputStreamR
import&mons.httpclient.methods.PostM
import&mons.httpclient.*;
public&class&H_client_post&{
public&static&void&main(String[]&args)&throws&IOException&{
HttpClient&client&=&new&HttpClient();
PostMethod&method&=&new&PostMethod("http://192.168.111.128/bak/login_post.php");
//表单域的值,既post传入的key=value
NameValuePair[]&date&=&{&new&NameValuePair("username","admin"),new&NameValuePair("password","123457")};
//method使用表单阈值
method.setRequestBody(date);
//提交表单
client.executeMethod(method);
//字符流转字节流&循环输出,同get解释
InputStream&inputStream&=&method.getResponseBodyAsStream();
BufferedReader&br&=&new&BufferedReader(new&InputStreamReader(inputStream,"UTF-8"));
StringBuffer&stringBuffer&=&new&StringBuffer();
String&str=&"";
while((str&=&br.readLine())&!=&null){&
stringBuffer&.append(str&);&
System.out.println(stringBuffer.toString());
method.releaseConnection();
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1
2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS协议。
4. 通过Http代理建立透明的连接。
5. 利用CONNECT方法通过Http代理建立隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
12. Request的输出流可以避免流中内容直接缓冲到socket服务器。
13. Response的输入流可以有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用KeepAlive保持持久连接。
15. 直接获取服务器发送的response code和 headers。
16. 设置连接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于Apache License 可免费获取。
三、使用方法
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
package com.
import java.io.F
import java.io.FileInputS
import java.io.IOE
import java.io.UnsupportedEncodingE
import java.security.KeyManagementE
import java.security.KeyS
import java.security.KeyStoreE
import java.security.NoSuchAlgorithmE
import java.security.cert.CertificateE
import java.util.ArrayL
import java.util.L
import javax.net.ssl.SSLC
import org.apache.http.HttpE
import org.apache.http.NameValueP
import org.apache.http.ParseE
import org.apache.http.client.ClientProtocolE
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.CloseableHttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.conn.ssl.SSLConnectionSocketF
import org.apache.http.conn.ssl.SSLC
import org.apache.http.conn.ssl.TrustSelfSignedS
import org.apache.http.entity.ContentT
import org.apache.http.entity.mime.MultipartEntityB
import org.apache.http.entity.mime.content.FileB
import org.apache.http.entity.mime.content.StringB
import org.apache.http.impl.client.CloseableHttpC
import org.apache.http.impl.client.HttpC
import org.apache.http.message.BasicNameValueP
import org.apache.http.util.EntityU
import org.junit.T
public class HttpClientTest {
public void jUnitTest() {
* HttpClient连接SSL
public void ssl() {
CloseableHttpClient httpclient =
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
// 加载keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
instream.close();
} catch (Exception ignore) {
// 相信自己的CA和所有自签名的证书
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 创建http请求(get方式)
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
} finally {
response.close();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* post方式提交表单(模拟用户登录请求)
public void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List&namevaluepair& formparams = new ArrayList&namevaluepair&();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefE
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
public void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List&namevaluepair& formparams = new ArrayList&namevaluepair&();
formparams.add(new BasicNameValuePair("type", "house"));
UrlEncodedFormEntity uefE
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 发送 get请求
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httpget.
HttpGet httpget = new HttpGet("/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
System.out.println("------------------------------------");
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
* 上传文件
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
EntityUtils.consume(resEntity);
} finally {
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}&/namevaluepair&&/namevaluepair&&/namevaluepair&&/namevaluepair&
以上这篇java发送HttpClient请求及接收请求结果过程的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具2011年1月 Java大版内专家分月排行榜第二
2002年6月 企业开发大版内专家分月排行榜第二
2002年4月 企业开发大版内专家分月排行榜第三
2002年6月 企业开发大版内专家分月排行榜第二
2002年4月 企业开发大版内专家分月排行榜第三
2002年6月 企业开发大版内专家分月排行榜第二
2002年4月 企业开发大版内专家分月排行榜第三
2010年8月 Java大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。HTTP POST数据和数据接收 - java小强博客
小强原创文章,java小强个人博客站点
当前位置:
>> HTTP POST数据和数据接收
又弄完一个项目,累成狗,但是感觉又进步不少,除了很多坑已经踩过,做起来也是轻车熟路。同时也认识到,程序不在于你多牛逼,而是在乎你的细节把控度,而细节的关注,是一个优秀程序员必须要注意的。另外,要相信自己,勇敢向前,没人生下来就是成功的,而且,成功的路,比成功本身更重要。 09:46
今日北京再次沙尘暴来袭,吃了几年细粮,终于能来口粗粮了,不过大早上看见这场景,还是吓我一跳,不过随后就平静了,毕竟是老朋友了。进公司又发现一股烤糊的味道,真是祸不单行啊,例外都是污染。发了两个口罩,开启保护模式。 10:16
今天同学问我,最近还在写代码吗?我想了想,这个问题怎么回答呢,我好像确实很长时间,虽然写了一些,但是主要内容已经不是写代码了。然后再想想,自己也7年多了,这么多年了,我收获了什么,我的目标到底是什么。眼看就奔三了,人生啊,开启感叹模式。 22:52
也许大家都已经注意到了,今年的房价,好多地方都是翻了一番,跟着就是,各地房东开始变相涨租。今年之所以搬走,就是为此,这两天同学也是如此。很多房东只认钱,别谈感情,伤钱。而对于这个城市来说,你怎么定位自己,你真把自己当成她的一份子?你来此为何?将来何去何从?自己掂量清楚。 10:03
为什么一直不写了呢?因为当爸爸了,没空了。今年的冬天,有些寒冷,除了这寒冬带来的不适,更有因乐视公司遇到危机,而带来的同事别离。送别同事,看着空旷的工位,心中有些悲凉。临近年关,此时此刻,该怎么做,似乎不再是脑子一热那么简单了。 11:28

我要回帖

更多关于 java http服务器 的文章

 

随机推荐