HTTP知识总结(三)HttpUrlConnection使用

参考内容:

1. Oracle Java HttpUrlConnection
2. Android Java HttpUrlConnection

在Android系统上和JRE上,Java HttpUrlConnection的API(使用方式)肯定是一样的,但是实现的细节并不一样。

 

一  GET

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by hongchang on 2018/11/15.
 */
public class GetExample {
    private String run(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            if (200 == urlConnection.getResponseCode()) {
                InputStream inputStream = urlConnection.getInputStream();
                byte[] data = new byte[512];
                StringBuilder builder = new StringBuilder();
                int len = 0;
                while (inputStream.read(data) != -1) {
                    builder.append(new String(data));
                }

                return builder.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        GetExample example = new GetExample();
        String result = example.run("https://raw.github.com/square/okhttp/master/README.md");
        System.out.print(result);
    }
}

二 POST

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by hongchang on 2018/11/15.
 */
public class PostExample {
    private String run(String urlStr, String json) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(100000);
            urlConnection.setRequestMethod("POST"); // 默认是 "GET"
            urlConnection.setRequestProperty("Content-type", "application/json");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(json.getBytes());
            outputStream.flush();
            outputStream.close();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder builder = new StringBuilder();
            byte[] data = new byte[1024];
            while (inputStream.read(data) != -1) {
                builder.append(new String(data));
            }
            inputStream.close();
            urlConnection.disconnect();
            return builder.toString();

        } catch (MalformedURLException malformedException) {
            System.out.print(malformedException.getMessage());
        } catch (IOException ioException) {
            System.out.print(ioException.getMessage());
        }

        return null;
    }

    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }

    public static void main(String[] args) throws IOException {
        PostExample example = new PostExample();
        String json = example.bowlingJson("Jesse", "Jake");
        String response = example.run("http://www.roundsapp.com/post", json);
        System.out.println(response);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值