http请求一个servlet(接口)地址

来源:互联网 发布:俄罗斯 叙利亚 知乎 编辑:程序博客网 时间:2024/06/02 07:30

以前测试一个自己写的接口总是用火狐浏览器的httpRequester进行请求,但是那个东西并不准确(有的时候能捕捉到没有被捕获的异常),而且后台上要跟其它的平台进行数据交互,想自己写一个http请求小方法然后进行测试,后台也能用上。MDZZ研究一上午,中午想明白了遂写代码测试成功,贴出来记录一下。

import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.Charset;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.InputStreamRequestEntity;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.commons.httpclient.params.HttpConnectionManagerParams;import org.apache.commons.httpclient.params.HttpMethodParams;import com.alibaba.fastjson.JSONObject;public class HttpClientTest {public static void main(String[] args) throws HttpException, IOException {//请求地址String url="http://xxxx:xxxx/xxxx/xxxxServlet";//组装请求数据JSONObject json=new JSONObject();JSONObject requestJson=new JSONObject();json.put("A", "A");json.put("B", "B");requestJson.put("C", "C");requestJson.put("D", "D");json.put("request", requestJson);/******正式的数据请求******/HttpClient client=new HttpClient();PostMethod method=new PostMethod(url);byte[] bytes = json.toString().getBytes("UTF-8");InputStream inputStream = new ByteArrayInputStream(bytes,0,bytes.length);//setRequestBody方法在http3.1之后被替换成setRequestEntityRequestEntity re=new InputStreamRequestEntity(inputStream,bytes.length,"charset=utf-8");method.setRequestEntity(re);method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");//设置超时的代码段HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();//设置连接超时时间(单位毫秒)managerParams.setConnectionTimeout(10000);//查看状态int status = client.executeMethod(method);if (status != HttpStatus.SC_OK) {System.out.println( "连接" + url+ "出错!错误代码为:" + status);throw new IllegalStateException("Method failed: "+ method.getStatusLine());}//处理返回的数据InputStream txtis = method.getResponseBodyAsStream();/* eclipse 环境开发环境迁移之后导致的返回报文乱码问题修改 */BufferedReader br = new BufferedReader(new InputStreamReader(txtis,Charset.forName("UTF-8")));//为了更直观的看到返回的数据而写的方法StringBuffer html = new StringBuffer(100);String tempbf;while ((tempbf = br.readLine()) != null) {html.append(tempbf);}method.releaseConnection();System.out.println(html.toString());}}


大致就是这样的请求方式,经测试暂无问题。还有一种接口的请求方式原理上大致就是在地址后面拼上参数然后整个长地址进行请求,只需把url后面拼完参数整个的地址请

求即可。上述方法如果有乱码的情况改改请求格式即可。













原创粉丝点击