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") + "\r\n");
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("\nTesting 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);

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM