java调用http请求的方法记录

编程

在工作中经常会遇到需要进行http的请求,各种姿势都有,今天先大体记录一下

第一种方式 :java原生(url.openStream(path)

//测试下载图片    

@Test

public void testDownloadImg(){

//图片url地址,百度上搜的

String imgSrc = "http://pic1.win4000.com/wallpaper/8/589c2f0f014ba.jpg",fileSrc = "D:\1.jpg";

//try with 写法,获取图片流

try(InputStream inputStream =new URL(imgSrc).openStream();

FileOutputStream fileOutputStream = new FileOutputStream(fileSrc)){

//把文件写到D盘根目录

int n;

byte[] buffer = new byte[1024];

while (-1 != (n = inputStream.read(buffer))) {

fileOutputStream.write(buffer, 0, n);

}

} catch (IOException e) {

e.printStackTrace();

}

}

//测试获取json字符串

@Test

public void testGetJson(){

//json文本地址,百度上随便搜的

try (InputStream inputStream = new URL("https://baike.baidu.com/cms/home/eventsOnHistory/11.json").openStream();

BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))){

//inputStream转成string输出

StringBuffer buffer = new StringBuffer();

String line;

while ((line = in.readLine()) != null){

buffer.append(line);

}

System.out.println(buffer);

} catch (IOException e) {

e.printStackTrace();

}

}

这种方式很简洁,用起来也舒服,用来获取文本和图片都比较适用

需要注意的是:获取inputStream后用缓存的方式读,不然会获取不完整,下面是错误的写法

/*不要用这种方式写图片,*/

/*byte[] bytes = new byte[inputStream.available()];

inputStream.read(bytes);

fileOutputStream.write(bytes);*/

/*不要用这种方式读文本*/

/*byte[] bytes = new byte[inputStream.available()];

inputStream.read(bytes);

String str = new String(bytes);

System.out.println(str);*/

url.openStream(path)在get方式请求下很好用了,如果碰到需要post方式请求,就不能用openStream这个方法了,需要改成用openConnection,获取连接对象都,对连接对象属性进行设置

public static void testUrlPost() throws IOException{

// Post请求的url,与get不同的是不需要带参数

URL postUrl = new URL("http://...");

// 打开连接

HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true

connection.setDoOutput(true);

// Read from the connection. Default is true.

connection.setDoInput(true);

// Set the post method. Default is GET

connection.setRequestMethod("POST");

// Post 请求不能使用缓存

connection.setUseCaches(false);

// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数

connection.setInstanceFollowRedirects(true);

/*配置本次连接的Content-type,配置为application/x-www-form-urlencoded的

意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode

进行编码*/

connection.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded");

// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,

// 要注意的是connection.getOutputStream会隐含的进行connect。

connection.connect();

DataOutputStream out = new DataOutputStream(connection

.getOutputStream());

// 参数

String content = "[{name:yy,id:123}]";

// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面

// 也可以用OutputStreamWriter,把writeBytes换成append

out.writeBytes(content);

out.flush();

out.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(

connection.getInputStream()));

String line;

while ((line = reader.readLine()) != null){

System.out.println(line);

}

reader.close();

connection.disconnect();

}

第二种方式:HttpClent , 依赖于Httpclent这个包

pom引用

         <dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.5.5</version>

</dependency>

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpcore</artifactId>

<version>4.4.9</version>

</dependency>

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpmime</artifactId>

<version>4.5.6</version>

</dependency>

get请求

@Test

public void testHttpClentGet(){

try (CloseableHttpClient client = HttpClients.createDefault()) {

HttpGet get = new HttpGet("https://baike.baidu.com/cms/home/eventsOnHistory/11.json");

try (CloseableHttpResponse response = client.execute(get);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

StringBuffer buffer = new StringBuffer();

String line;

while ((line = reader.readLine()) != null){

buffer.append(line);

}

System.out.println(buffer);

}

} catch (Exception e) {

e.printStackTrace();

}

}

get请求是表现不出httpClent的强大之处,只是get请求的话,单纯用jdk自带的就好了,一些涉及复杂的交互的时候,httpclent才可以展现它的强大

post请求

 /**

* 测试推送json字符串的post

*/

public void testHttpClentPostString(){

try (CloseableHttpClient client = HttpClients.createDefault()) {

HttpPost post = new HttpPost("http://...");

String content = "[{name:yy,id:123}]";

//放入需要推送的数据,并设置编码(防止中文乱码)

StringEntity stringEntity = new StringEntity(content,"utf-8");

stringEntity.setContentType("utf-8");

post.setHeader("Content-type","application/json;charset=utf-8");

post.setEntity(stringEntity);

try (CloseableHttpResponse response = client.execute(post);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

StringBuffer buffer = new StringBuffer();

String line;

while ((line = reader.readLine()) != null){

buffer.append(line);

}

System.out.println(buffer);

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 测试推送推送多个对象的post

*/

public void testHttpClentPostObject(){

try (CloseableHttpClient client = HttpClients.createDefault()) {

HttpPost post = new HttpPost("http://...");

List<BasicNameValuePair> list = new ArrayList<>();

list.add(new BasicNameValuePair("id","123"));

list.add(new BasicNameValuePair("name","san"));

list.add(new BasicNameValuePair("age","16"));

HttpEntity entity = new UrlEncodedFormEntity(list,"utf-8");

post.setEntity(entity);

post.setHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");

try (CloseableHttpResponse response = client.execute(post);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

StringBuffer buffer = new StringBuffer();

String line;

while ((line = reader.readLine()) != null){

buffer.append(line);

}

System.out.println(buffer);

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 推送的数据中有byte字节流文件 post 请求

*/

public void testHttpClentPostByte(byte[] b){

try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

HttpPost post = new HttpPost("http://...");

ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));

MultipartEntityBuilder meb = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

meb.addTextBody("title", "测试标题", contentType);

meb.addTextBody("content", "文件内容", contentType);

meb.addBinaryBody("file", b, ContentType.MULTIPART_FORM_DATA, "img.jpg");

HttpEntity entity = meb.build();

post.setEntity(entity);

try (CloseableHttpResponse response = client.execute(post);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

StringBuffer buffer = new StringBuffer();

String line;

while ((line = reader.readLine()) != null){

buffer.append(line);

}

System.out.println(buffer);

}

} catch (Exception e) {

e.printStackTrace();

}

}

强大的httpclent可以搞定你碰到的所有奇葩http请求

以上是 java调用http请求的方法记录 的全部内容, 来源链接: utcz.com/z/511046.html

回到顶部