java原生get和post请求(基于java 1.8)

Posted Moucong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java原生get和post请求(基于java 1.8)相关的知识,希望对你有一定的参考价值。

package com.moucong;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;

public class get_post {

/**
* Created by chengxia on 2018/12/4.
*/
public String doPost(String URL){
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try{
URL url = new URL(URL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//发送POST请求必须设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//获取输出流
out = new OutputStreamWriter(conn.getOutputStream());
//向post请求发送json数据
String jsonStr = "{"touser":"", "msgtype":"text", "text":{" +
" "content":""}}";
out.write(jsonStr);
out.flush();
out.close();
//取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}
return result.toString();
}

public String doGet(String URL){
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try{
//创建远程url连接对象
URL url = new URL(URL);
//通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//通过conn取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()){
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null){
result.append(line);
// System.out.println(line);
}
//json类型字符串转为jsonObject
// System.out.println(result);
JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
//根据key值获取数据value
System.out.println(jsonObject.getString("access_token")); //输出value1
Writer writer = null;
StringBuilder outputString = new StringBuilder();
try {
outputString.append(jsonObject.getString("access_token") + " ");
writer = new FileWriter("test.txt"); // true表示追加
writer.write(outputString.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}



}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
conn.disconnect();
}
return result.toString();
}


/** 读取文件数据,存入集合中
* @return*/
public static String readtFile(File file) throws IOException, ParseException {
InputStreamReader read = null;// 考虑到编码格式
try {
read = new InputStreamReader(new FileInputStream(file), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
StringBuffer buffer = new StringBuffer();
String line = " ";
while ((line = bufferedReader.readLine()) != null) {
// System.out.println(lineTxt);
buffer.append(line);
}

read.close();
return buffer.toString();
}


public static void main(String[] args) throws Exception {
get_post http = new get_post();

// System.out.println("Testing 1 - Do Http GET request");
//获取token的get方法
// http.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=");

System.out.println(" Testing 2 - Do Http POST request");
File file = new File("test.txt");
String token = readtFile(file);
System.out.println(token);
http.doPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token);

}

}

以上是关于java原生get和post请求(基于java 1.8)的主要内容,如果未能解决你的问题,请参考以下文章

Java学习心得之 HttpClient的GET和POST请求

Java实现post和get请求

原生Get请求和Post请求

java 用Java发送GET和POST请求

java基础之get和post的差别

java如何得到GET和POST请求URL和参数列表