java发送HttpClient请求及接收请求结果过程的简单实例
发布时间:2020-12-15 14:23:27  所属栏目:Java  来源:互联网 
            导读:一.1、写一个HttpRequestUtils工具类,包括post请求和get请求packagecom.brainlong.framework.util.httpclient;
                
                
                
            | 
                         一. 1、写一个HttpRequestUtils工具类,包括post请求和get请求 
package com.brainlong.framework.util.httpclient; 
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 
import java.io.IOException;import java.net.URLDecoder; public class HttpRequestUtils {  
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);  
//日志记录   /**   * httpPost   * @param url 路径   * @param jsonParam 参数   * @return   */  
public static JSONObject httpPost(String url,JSONObject jsonParam){    
return httpPost(url,jsonParam,false);  
}   
/**   * post请求   * @param url     url地址   * @param jsonParam   参数   * @param noNeedResponse  不需要返回结果   * @return   */  
public static JSONObject httpPost(String url,JSONObject jsonParam,boolean noNeedResponse){    
//post请求返回结果    
DefaultHttpClient httpClient = new DefaultHttpClient();    
JSONObject jsonResult = null;    
HttpPost method = new HttpPost(url);    
try {      
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 = "";        
try {          
/**读取服务器返回过来的json字符串数据**/          
str = EntityUtils.toString(result.getEntity());          
if (noNeedResponse) {            
return null;          
}          
/**把json字符串转换成json对象**/          
jsonResult = JSONObject.fromObject(str);        
} catch (Exception e) {          
logger.error("post请求提交失败:" + url,e);        
}      
}    
} catch (IOException e) {      
logger.error("post请求提交失败:" + url,e);    
}    
return jsonResult;  
}   
/**   * 发送get请求   * @param url  路径   * @return   */  
public static JSONObject httpGet(String url){    
//get请求返回结果    
JSONObject jsonResult = null;    
try {      
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");      
} else {        
logger.error("get请求提交失败:" + url);      
}    
} catch (IOException e) {      
logger.error("get请求提交失败:" + url,e);    
}    
return jsonResult;  }}
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 exceptionInfoBiz;
/**
* 创建异常信息请求
* @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 smsSendBiz;
/**
* 接收手机号码和内容往短信发送表插入一条记录
* @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));
}
}
二. get 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
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=admin@admin.com&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();
}
}
                        (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
