现在虽然HttpClient很好使,但也有人在用最原生的HttpURLConnection, 记录一下,备忘之。

public class HttpUrlConnect {
//get请求
public String get(String url){
HttpURLConnection conn = null;
BufferedReader rd = null ;
StringBuilder sb = new StringBuilder ();
String line = null ;
String response = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
conn.connect();
rd = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = rd.readLine()) != null ) {
sb.append(line);
}
response = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(rd != null){
rd.close();
}
if(conn != null){
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
//post表单请求
public String post(String url, Map<String, String> form){
HttpURLConnection conn = null;
PrintWriter pw = null ;
BufferedReader rd = null ;
StringBuilder out = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = null ;
String response = null;
for (String key : form.keySet()) {
if(out.length()!=0){
out.append("&");
}
out.append(key).append("=").append(form.get(key));
}
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
conn.connect();
pw = new PrintWriter(conn.getOutputStream());
pw.print(out.toString());
pw.flush();
rd = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = rd.readLine()) != null ) {
sb.append(line);
}
response = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(pw != null){
pw.close();
}
if(rd != null){
rd.close();
}
if(conn != null){
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
//post字符串请求
public String post(String url, String rawBody){
HttpURLConnection conn = null;
PrintWriter pw = null ;
BufferedReader rd = null ;
StringBuilder sb = new StringBuilder ();
String line = null ;
String response = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
conn.connect();
pw = new PrintWriter(conn.getOutputStream());
pw.print(rawBody);
pw.flush();
rd = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = rd.readLine()) != null ) {
sb.append(line);
}
response = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(pw != null){
pw.close();
}
if(rd != null){
rd.close();
}
if(conn != null){
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
} public static void main(String[] args) {
HttpUrlConnect h = new HttpUrlConnect();
System.out.println(h.get(""));
Map<String, String> form = new HashMap<String, String>();
form.put("test", "test");
System.out.println(h.post("", form));
} }

HttpURLConnection GET/POST写法的更多相关文章

  1. Android入门(二十)HttpURLConnection与HttpClient

    原文链接:http://www.orlion.ga/679/ 在 Android上发送 HTTP请求的方式一般有两种,HttpURLConnection和 HttpClient. 一.HttpURLC ...

  2. Android回调接口的写法

    方法一: 定义一个接口,里面写想要对外提供的方法,在逻辑层方法的参数里传递进去,让在需要的时候调接口里的方法. 实例一: public class SmsUtils { public interfac ...

  3. 使用HttpURLConnection实现在android客户端和服务器之间传递对象

    一般情况下,客户端和服务端的数据交互都是使用json和XML,相比于XML,json更加轻量级,并且省流量,但是,无论我们用json还是用xml,都需要我们先将数据封装成json字符串或者是一个xml ...

  4. 关于HttpClient,HttpURLConnection,OkHttp的用法

    1 HttpClient入门实例 1.1发送get请求 /** * HttpClient发送get请求 * @param url 请求地址 * @return * @throws IOExceptio ...

  5. Java HttpURLConnection模拟请求Rest接口解决中文乱码问题

    转自:http://blog.csdn.net/hwj3747/article/details/53635539 在Java使用HttpURLConnection请求rest接口的时候出现了POST请 ...

  6. 转 关于HttpClient,HttpURLConnection,OkHttp的用法

    转自:https://www.cnblogs.com/zp-uestc/p/10371012.html 1 HttpClient入门实例 1.1发送get请求 1 2 3 4 5 6 7 8 9 10 ...

  7. HttpUrlConnection 基础使用

    From https://developer.android.com/reference/java/net/HttpURLConnection.html HttpUrlConnection: A UR ...

  8. obj.style.z-index的正确写法

    obj.style.z-index的正确写法 今天发现obj.style.z-index在js里面报错,后来才知道在js里应该把含"-"的字符写成驼峰式,例如obj.style.z ...

  9. java设计模式之单例模式(几种写法及比较)

    概念: Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单例类只能有一个实例. 2.单例类必须自己创建 ...

随机推荐

  1. php执行流程

    1.源码文件编写,php源文件 2.词法分析,token 3.语法分析,生成opcode并组成opcode array 4.执行opcode,返回结果

  2. JS-怎么得到局部域中的数据

    1,使用全局变量 var str = '';function fn1(){    var a = '大鸡腿~';    str = a;} 2,使用一个局部函数 function fn2(){     ...

  3. (转)ASP.NET Mvc 2.0 - 1. Areas的创建与执行

    转自:http://www.cnblogs.com/terrysun/archive/2010/04/13/1711218.html ASP.NET Mvc 2.0 - 1. Areas的创建与执行 ...

  4. [Leetcode][JAVA] Palindrome Partitioning II

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

  5. iOS 开发者必知的 75 个工具(译文)

    原文地址:http://benscheirman.com/2013/08/the-ios-developers-toolbelt (需FQ)   如果你去到一位熟练的木匠的工作室,你总是能发现他/她有 ...

  6. 20145301&20145321&20145335实验一

    这次实验我的组员为:20145301赵嘉鑫.20145321曾子誉.20145335郝昊 实验内容详见:实验一报告

  7. JQuery学习(选择器-可见性-hidden)

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...

  8. Incompatible operand types DeptE and int 异常处理

    Incompatible operand types DeptE and int 1.java不会运算到==的值,把==改为equals 2.java不会运算到eequals的值 把equals的改为 ...

  9. Magicodes.WeiChat——使用AntiXssAttribute阻止XSS(跨站脚本攻击)攻击

    跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻击者往Web页面里插 ...

  10. SVEditor 1.3.6 发布

    SVEditor 1.3.6 支持代码高亮时没有处理 #ifdefs 语句的问题,支持类.接口.模块.任务和函数的代码折叠,修复了一些 bug. SVEditor 是一个Eclipse的插件,用来编辑 ...