博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java HTTP通信--Get与POST请求
阅读量:4964 次
发布时间:2019-06-12

本文共 5578 字,大约阅读时间需要 18 分钟。

一、JDK自带的http通信机制--java.net.URL

package com.wjy;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 TestURL {    public static void main(String[] args) {        new GetRun().start();//get请求        new PostRun().start();//post请求    }}class GetRun extends Thread{    public void run() {        try {            //doctype=xml/json/jsonp            URL url = new URL("http://fanyi.youdao.com/openapi.do?keyfrom=wjy-test&key=36384249&type=data&doctype=jsonp&callback=show&version=1.1&q=hello");            URLConnection connection = url.openConnection();            InputStream in = connection.getInputStream();            InputStreamReader isr = new InputStreamReader(in,"utf-8");            BufferedReader br = new BufferedReader(isr);            String line;            StringBuilder sb = new StringBuilder();            while((line = br.readLine()) != null)            {                sb.append(line);            }            br.close();            isr.close();            in.close();            System.out.println(sb.toString());        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}class PostRun extends Thread{    @Override    public void run() {        try {            URL url = new URL("http://fanyi.youdao.com/openapi.do");            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.addRequestProperty("encoding", "UTF-8");//添加请求属性            connection.setDoInput(true);//允许输入            connection.setDoOutput(true);//允许输出            connection.setRequestMethod("POST");//POST请求 要在获取输入输出流之前设置  否则报错            //输出            OutputStream os = connection.getOutputStream();            OutputStreamWriter osw = new OutputStreamWriter(os);            BufferedWriter bw = new BufferedWriter(osw);            bw.write("keyfrom=wjy-test&key=36384249&type=data&doctype=xml&version=1.1&q=welcome");            bw.flush();                        //输入            InputStream in = connection.getInputStream();            InputStreamReader isr = new InputStreamReader(in,"UTF-8");            BufferedReader br = new BufferedReader(isr);                        String line;            StringBuilder sb = new StringBuilder();            while((line = br.readLine()) != null)            {                sb.append(line);            }            bw.close();            osw.close();            os.close();            br.close();            isr.close();            in.close();                        System.out.println(sb.toString());                    } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }            }    }

 

二、apache中HttpComponents项目HttpClient工具

package com.wjy;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;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.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class TestHttpclient {    /**     * 从apache官网下载HttpComponents项目jar包     */    public static void main(String[] args) {        //new Get().start();        new Post().start();    }}class Get extends Thread{    HttpClient client = HttpClients.createDefault();        @Override    public void run() {        HttpGet get = new HttpGet("http://www.baidu.com");        try {            HttpResponse response = client.execute(get);            HttpEntity entity = response.getEntity();            String result = EntityUtils.toString(entity, "UTF-8");            System.out.println(result);        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }            }}class Post extends Thread{HttpClient client = HttpClients.createDefault();        @Override    public void run() {        HttpPost post = new HttpPost("http://fanyi.youdao.com/openapi.do");        try {            List
parameters = new ArrayList
(); parameters.add(new BasicNameValuePair("keyfrom", "wjy-test")); parameters.add(new BasicNameValuePair("key", "36384249")); parameters.add(new BasicNameValuePair("type", "data")); parameters.add(new BasicNameValuePair("doctype", "xml")); parameters.add(new BasicNameValuePair("version", "1.1")); parameters.add(new BasicNameValuePair("q", "welcome")); post.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}

 

转载于:https://www.cnblogs.com/cac2020/p/6675794.html

你可能感兴趣的文章
BNU34058——干了这桶冰红茶!——————【递推】
查看>>
安装两个JDK后配置环境变量没用?
查看>>
ASP.NET MVC网站开发流程
查看>>
C# url信息获取
查看>>
20155212 2017.05.17课堂代码实践总结
查看>>
(笔记)Linux内核学习(一)之内核介绍
查看>>
angular双向数据绑定
查看>>
ioc控制反转
查看>>
算法与数据结构 (四) 排序 一 交换类排序
查看>>
Windows Server 2012 虚拟化实战:网络(二)
查看>>
TCP与UDP的区别
查看>>
PHP循环while do while循环
查看>>
如何设置linux启动过程中的停止阶段
查看>>
Codeforces Round #246 (Div. 2)
查看>>
进程管理之基本概念
查看>>
nginx mac
查看>>
【转-整理】Spring的Ioc理解,写的很通俗易懂
查看>>
第一篇
查看>>
[USACO13JAN] Cow Lineup (单调队列,尺取法)
查看>>
jeasyui 中文网
查看>>