package com.httpPostTest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpPostTest { public static void main(String[] args) { CreatHttpUrl creatUrl = new CreatHttpUrl(); String urlStr = "https://openapi.youdao.com/api"; String paramStr = creatUrl.createParam("good","en","zh-CHS"); System.out.println(paramStr); try { //设置请求相关设置 URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("encoding", "UTF-8"); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); //post提交数据 OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter writer = new BufferedWriter(osw); writer.write(paramStr); writer.flush(); //读取获取的数据 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder builder = new StringBuilder(); while((line = br.readLine()) != null) { builder.append(line); } writer.close(); osw.close(); os.close(); br.close(); isr.close(); is.close(); System.out.print(builder.toString()); } catch (Exception e) { e.printStackTrace(); } } }
post请求
猜你喜欢
转载自blog.csdn.net/qq_40955914/article/details/80173722
今日推荐
周排行