HttpUrlConnection使用Get和Post访问服务器的工具类(一)
首先我们有一个返回响应的接口HttpCallBackListener
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
然后就是工具类的主体了
import android.util.Log; import org.json.JSONObject; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader; import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map; public class HttpUtil {
//使用Get方法,path存储一个网址,Map存储一个键值对
public static void sendHttpRequestForGet(final String path,final Map<String,String> params , final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null; try{
StringBuilder stringBuilder=new StringBuilder();
StringBuilder response=new StringBuilder();
stringBuilder.append(path).append("?");
if(params!=null&¶ms.size()!=0){
for(Map.Entry<String,String> entry:params.entrySet()){
//转换成UTF-8
stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"utf-8"));
stringBuilder.append("&");
}
//删除最后一个字符&
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
//此时网址变长了,增加了Map中的内容
URL url=new URL(stringBuilder.toString());
//打印网址
Log.e("HttpUtil",stringBuilder.toString()); connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(100000);
connection.setReadTimeout(100000);
connection.setRequestProperty("Content-Type", "application/json");
//200表示连接成功
if(connection.getResponseCode()==200){
InputStream in=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"utf-8"));
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
}else{
System.out.println(connection.getResponseCode());
Log.e("HttpUtil","fail");
}
if(listener!=null){
Log.e("HttpUtil",response.toString());
//把response转换为String类型再作为参数传入,以便调用他的类访问
listener.onFinish(response.toString());
}
}catch(Exception e){
if (listener!=null){
listener.onError(e);
}
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
} public static void sendHttpRequestForPost(final String path,final Map<String,String> paramsValue, final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
try{
StringBuilder response=new StringBuilder();
JSONObject jsonObject = new JSONObject();
for(Map.Entry<String,String> entry:paramsValue.entrySet()){
jsonObject.put(entry.getKey(),entry.getValue());
}
URL url=new URL(path);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(100000);
connection.setReadTimeout(100000);
connection.setDoOutput(true);
connection.setDoInput(true);
//千万要记着这个setRequestProperty
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
Log.d("HttpUtil", jsonObject.toString());
//将数据写给服务器
DataOutputStream out= new DataOutputStream(connection.getOutputStream());
out.writeBytes(jsonObject.toString());
Log.d("HttpUtil",jsonObject.toString());
//成功
if(connection.getResponseCode()==200){
Log.d("HttpUtil", "success");
InputStream in=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"utf-8"));
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
}else{
Log.e("HttpUtil",Integer.toString(connection.getResponseCode()));
Log.e("HttpUtil","fail");
}
if(listener!=null){
Log.e("HttpUtil","注册成功");
Log.e("HttpUtil",response.toString());
listener.onFinish(response.toString());
}
}catch(Exception e){
if (listener!=null){
Log.d("HttpUtil",e.getMessage());
listener.onError(e);
}
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
假设我们要在MainActivity中访问
httpUtil.sendHttpRequestForGet("http://210.38.111.146:8080/WindBell/rest/login", map, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
//得到了response后就方便多了
}
@Override
public void onError(Exception e) {
}
});
HttpUrlConnection使用Get和Post访问服务器的工具类(一)的更多相关文章
- OkHttp使用Get和Post访问服务器的工具类(一)
首先来简单介绍一下okttp框架,类似于HttpUrlConnection,Android6.0以后,废弃了Apache Http Client,只有HttpUrlConnection和OkHttp了 ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- 分享自己配置的HttpURLConnection请求数据工具类
>>该工具类传入string类型url返回string类型获取结果import java.io.BufferedReader;import java.io.InputStream;impo ...
- java工具类
1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- Android开发常用工具类
来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...
- HttpTool.java(在java tool util工具类中已存在) 暂保留
HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...
- 53. Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...
- android下载简单工具类
功能是实现下载文件,图片或MP3等,为了简单起见使用单线程,此代码为MarsAndroid教程的复制品,放在此处,留着参考. 首先是一个得到字节流随后保存到内存卡上的工具类: package com. ...
随机推荐
- storm(一) window机制
Watermark作用 在解释storm的window之前先说明一下watermark原理. Watermark中文翻译为水位线更为恰当. 顺序的数据从源头开始发送到到操作,中间过程肯定会出现数据乱序 ...
- 【Network Architecture】Densely Connected Convolutional Networks 论文解析
目录 0. Paper link 1. Overview 2. DenseNet Architecture 2.1 Analogy to ResNet 2.2 Composite function 2 ...
- Python学习札记(十三) Function3 函数参数二
参考:函数参数 Note A.关键字参数: 1.关键字参数:**kw 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple.而关键字参数允许你传入0个或任意个含参数名的 ...
- P4开源Tutorials教程样例实战及对P4v1.1规范的初分析
Github链接:Github-P4Lang-Tutorials-p4v1.1 前言 本文主要对Barefoot开源教程中的p4v1.1实例simple_router的实战步骤进行记录与阐述,希望能帮 ...
- Codeforces Round #360 (Div. 2) D. Remainders Game
D. Remainders Game time limit per test 1 second memory limit per test 256 megabytes input standard i ...
- ubuntu如何U盘启 动制作
先到出 U盘的位置, 方法有很多,terminal 用root权限,采用fdisk -f 命令 unmount /dev/sdb -I //U盘拨出 sdb为U盘挂载的位置 mkfs.fat /dev ...
- TensorFlow备忘录——conv2d函数
卷积函数 TensorFlow学习备忘录 tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_forma ...
- Android 进行解析并显示服务端返回的数据
例子说明:用户通过访问web资源的最新电影资讯,服务器端生成XML或JSON格式数据,返回Android客户端进行显示. 此案例开发需要两个方面 WEB开发和Android开发. 一.web开发相对比 ...
- stdclass
$item = new stdClass(); $item->goods_id = $item_goods->getID(); $item->goods_name ...
- Intellij IDEA的一些操作小技巧
1.Presentation Mode 我们可以使用 Presentation Mode,将IDEA弄到最大,可以让你只关注一个类里面的代码,进行毫无干扰的 coding.可以使用Alt+v快捷键,弹 ...