java发送http的get、post请求(二) 使用Object接收返回值处理及新旧版本对比

java发送http的get、post请求(二) 使用Object接收返回值处理

参考网址:
https://www.iteye.com/blog/gaozzsoft-2352311, 如有侵权联系删除!

Java处理Http请求的几种方式总结:

1.commons-httpclient 简洁快速模拟HTTP请求

<dependency>
	<groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
 </dependency>

(1) 代码如下

import java.io.IOException;


import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.methods.PostMethod;

 

/**

 * Hello world!

 * 

 */

public class App {

private static final HttpClient client = new HttpClient();

public static void main(String[] args) throws HttpException, IOException, InterruptedException {

for (int i = 0; i < 2000; i++) {

PostMethod method = new PostMethod("http://open.kaduoyun.com/api/v1.0/sendMsg.htm");

//http://localhost:8080/vs-rest/rs/user/register/gaozz/jerrison/gaozhenzhai@126.com/123456/test/0/30/addrtest/18600635193/touxiang/1100

method.getParams().setContentCharset("UTF-8");

method.addParameter("appkey", "38F325796F584656946801146D177C18");

method.addParameter("appsecret", "4451E66CDBAE8C01FC1B12D70CDFA077");

method.addParameter("title", "测试标题");

method.addParameter("content", "测试内容"+i);

//method.addParameter("clientid", "");

client.executeMethod(method);

System.out.println(method.getResponseBodyAsString()+i);

Thread.sleep(10);

}

}

}

 (2)

import java.io.IOException;

 

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.methods.PostMethod;

 

/**
 * Hello world!
 * 
 */

public class UserTestApp {

private static final HttpClient client = new HttpClient();
private static  final String urlStr = "http://192.168.0.117:8080";
//private static  final String urlStr = "http://192.168.0.110:8080/vs-rest";
public static void main(String[] args) throws HttpException, IOException, InterruptedException {

//testLogin();

//testSearchCity();

//testRegister();

testFindPassword();

//testVerifyUnique();

//testUpdateUserInfo();

//testSearch();

//testSchoolCompetitor();

//testSignUp();

//testVote();

}

 

public static void testRegister() throws HttpException, IOException, InterruptedException{

PostMethod method = new PostMethod(urlStr+"/rs/user/register");

//http://localhost:8080/vs-rest/rs/user/register/gaozz/jerrison/gaozhenzhai@126.com/123456/test/0/30/addrtest/18600635193/touxiang/1100

method.getParams().setContentCharset("UTF-8");

method.addParameter("userName", "gaozz");

method.addParameter("nickName", "jerrison11");

method.addParameter("email", "gaozhenzhai11@126.com");  

method.addParameter("password", "123456"); 

method.addParameter("equipmentId", "test818"); 

method.addParameter("sex", "0");  

method.addParameter("age", "30"); 

method.addParameter("addr", "addrtest");  

method.addParameter("phone", "18600635193"); 

method.addParameter("avatar", "touxiang");

method.addParameter("birthday", "1100");

client.executeMethod(method);

System.out.println(method.getResponseBodyAsString());

Thread.sleep(10);

}

 

public static void testLogin() throws HttpException, IOException, InterruptedException{

PostMethod method = new PostMethod(urlStr+"/rs/user/login");

method.getParams().setContentCharset("UTF-8");

method.addParameter("userName", "gaozz");

method.addParameter("password", "654321"); 

client.executeMethod(method);

System.out.println(method.getResponseBodyAsString());

Thread.sleep(10);

}

 

 

public static void testFindPassword() throws HttpException, IOException, InterruptedException{

PostMethod method = new PostMethod(urlStr+"/rs/user/findPassword");

method.getParams().setContentCharset("UTF-8");

method.addParameter("userName", "slaton");

method.addParameter("verifyCode", "060468");

method.addParameter("newPassword", "12345678");

client.executeMethod(method);

System.out.println(method.getResponseBodyAsString());

Thread.sleep(10);

}
}

2.apache org.apache.httpcomponents httpclient

 <dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.2</version>
</dependency>

参考new version 4.5 新版本代码如下:

importorg.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;


public static String httpPostUrlForPdf(String url) {
    // 设置HTTP请求参数
String result = null;
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {
        CloseableHttpResponse response = client.execute(httpGet);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ClientProtocolException e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } catch (IOException e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            logger.error("http接口调用异常:url is::" + url, e);
        }
    }
    return result;
}

old version 4.3版本代码如下 :

public static String httpPost(String url, String jsonString) {
    // 设置HTTP请求参数
String result = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);//设置请求超时时间 10s
StringEntity entity = new StringEntity(jsonString);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpEntity resEntity = httpClient.execute(httpPost).getEntity();
        result = EntityUtils.toString(resEntity, "UTF-8");
    } catch (Exception e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

调用代码如下:

ReqChedaiParamDataVo dataVo = new ReqChedaiParamDataVo();
dataVo.setIdCard(idCard);
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", dataVo);
String jsonString = JSONObject.toJSONString(map);
LOGGER.info("请求对象json::" + jsonString);
String response = HttpUtils.httpPost(queryMemberInfoHttpUrl, jsonString);
LOGGER.info("响应字符串::" + response);

Another:

HttpPost httpPost22 = new HttpPost("http://test.com/abc");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));

try {
    httpPost22.setEntity(new UrlEncodedFormEntity(nvps));
    httpClient.execute(httpPost);
} catch (IOException e) {
    e.printStackTrace();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Cloud 中,可以使用 Zuul 作为 API 网关,通过 Zuul 进行请求转发和路由。而 Zuul 还提供了过滤器(Filter)机制,可以在请求被路由到目标服务前、后进行一些预处理或后处理。 在 Zuul 中,过滤器分为四种类型: 1. Pre:在请求被路由到目标服务前执行; 2. Post:在请求被路由到目标服务后执行; 3. Route:用于将请求路由到目标服务的过程中执行; 4. Error:在请求发生错误时执行。 通过实现 Zuul 的过滤器接口,可以自定义过滤器,并指定过滤器的类型和执行顺序。在过滤器中,可以对请求或响应进行修改或者拦截。 对于过滤器的返回值拦截,可以在 Pre 和 Error 类型的过滤器中进行。在 Pre 类型的过滤器中,可以通过抛出异常的方式终止请求,并将异常信息返回给客户端。在 Error 类型的过滤器中,可以通过设置响应状态码、响应头信息等方式,修改响应内容。 例如,在 Pre 类型的过滤器中,可以通过以下代码实现返回拦截: ```java public class AuthFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String authToken = request.getHeader("Authorization"); if (StringUtils.isBlank(authToken)) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); ctx.setResponseBody("Unauthorized"); return null; } return null; } } ``` 在该过滤器中,如果请求头中不存在 Authorization 字段,则设置返回状态码为 401,并设置响应内容为 "Unauthorized",从而实现了返回值拦截。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值