分享自己配置的HttpURLConnection请求数据工具类
>>该工具类传入string类型url返回string类型获取结果
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder; /**
* Created by ZJQ on 2016/5/20.
*/
//获取网络返回数据
public class GetNetJson { public String getJson(String urlstring) {
String result = "";
try {
URL url = new URL(urlstring);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(4000);
connection.setRequestMethod("GET");
//设置通讯的头部信息,设置访问方式
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//获取流
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
while ((tempLine = br.readLine()) != null) {
resultBuffer.append(tempLine);
}
result = resultBuffer.toString();
br.close();
inputStream.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
>>期初由于该没有设置该属性导致app无法连接到网络
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
调用方式:
String result = getNetJson.getJson("www.baidu.com");
以下是最近(18年8月)才写的urlconnection类,其实httpurlconectin是URLConnection的子类,看过源码的都知道。所以他俩大同小异
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map; public class RequestPayTool {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + param;
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setConnectTimeout(60000);
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "" + line;
}
} catch (Exception e) {
System.out.println("##发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送POST方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, String param,int timeOut) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
conn.setConnectTimeout(timeOut);
// 设置通用的请求属性
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "" + line;
}
} catch (Exception e) {
System.out.println("##发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
分享自己配置的HttpURLConnection请求数据工具类的更多相关文章
- 获取post请求数据工具类
package com.ccidit.features.otherFunctions.util; import java.io.BufferedReader; import java.io.IOExc ...
- HttpUtils 用于进行网络请求的工具类
原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...
- HTTP请求客户端工具类
1.maven 引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId> ...
- 发送http请求和https请求的工具类
package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...
- java中模拟http(https)请求的工具类
在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应.比如我们想访问微信接口,获取其返回信息. 在 ...
- 高德地图web端笔记;发送http请求的工具类
1.查询所有电子围栏 package com.skjd.util; import java.io.BufferedReader; import java.io.InputStream; import ...
- 基于AFNetWorking 3.0封装网络请求数据的类
对于使用 AFNetworking 的朋友来说,很多朋友都是直接调用 AFNetworking的 API ,这样不太好,无法做到全工程统一配置. 最好的方式就是对网络层再封装一层,全工程不允许直接使用 ...
- Android分享到微信和朋友圈的工具类
1.只要填写上正确的app_id,且引用上该工具类你就能实现分享到朋友圈和分享到微信. 2.需要到微信平台下载jar包,以及注册一个appid import android.content.Conte ...
- 使用java多线程分批处理数据工具类
最近由于业务需要,数据量比较大,需要使用多线程来分批处理,提高处理效率和能力,于是就写了一个通用的多线程处理工具,只需要实现自己的业务逻辑就可以正常使用,现在记录一下 主要是针对大数据量list,将l ...
随机推荐
- 检测cpu是否支持虚拟化和二级地址转换【转】
SLAT:二级地址转换 用微软的小工具“Coreinfo.exe” 下载地址是: http://technet.microsoft.com/en-us/sysinternals/cc835722 ...
- it转行了
国庆节后毅然的辞职了,辞职的还发生一些不愉快的事情,原来希望好去好来却不慌而散.接着便开始找工作,有过工作经验,找工作是容易些,不像刚毕业那会什么企业都没人要.因为实在是对it没感觉,所以找的都是销售 ...
- html中offsetTop、clientTop、scrollTop、offsetTop各属性介绍
例如:$('window').scrollTop()获取的就是当前这个页面超出窗口最上端的高度,scrollLeft与此同理 scrollHeight: 获取对象的滚动高度. scrollLeft:该 ...
- 使用COALESCE时注意left join为null的情况
1.使用COALESCE时,用到group by with cube,如果之前两个表left join时,有数据为null,就会使得查出的数据主键不唯一 例如: select COALESCE (c. ...
- 网页 css 样式 初始化
body, div, ul, ol, dl, dt, dd, li, dl, h1, h2, h3, h4 {margin:0;padding:0;font-style:normal;font:12p ...
- 使用Autolayout对多行文本Label进行布局,高度不准确的解决办法!
BUG描述: 今天公司的项目中发现了一个BUG,大概给大家描述一下,tabbleView有一个tableFooterView,这个footView中有一个Label,是多行显示文本,程序用的是Auto ...
- github改local用户名和email
github改local用户名和email 进入cd ~/.ssh 修改git config --global user.name “用户名” config --global user.email 电 ...
- silk mpu
#include "mpu.h" #include "mbuf.h" #include "media_buffer.h" #include ...
- -bash: msgunfmt: command not found
执行命令:msgunfmt frontend.mo -o frontend.po 解决方法: 安装gettext完成后如下:
- Fair Scheduler中的Delay Schedule分析
延迟调度的主要目的是提高数据本地性(data locality),减少数据在网络中的传输.对于那些输入数据不在本地的MapTask,调度器将会延迟调度他们,而把slot分配给那些具备本地性的MapTa ...