ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2020-12-06 14:32:42  阅读:182  来源: 互联网

标签:http get Object addParameter org apache import method


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();
}

标签:http,get,Object,addParameter,org,apache,import,method
来源: https://blog.csdn.net/weixin_42134712/article/details/110734320

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有