HttpUrlConnection使用Get和Post访问服务器的工具类(一)
来源:互联网 发布:js选项卡自动切换 编辑:程序博客网 时间:2024/06/10 21:10
首先我们有一个返回响应的接口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) { } });
阅读全文
0 0
- HttpUrlConnection使用Get和Post访问服务器的工具类(一)
- OkHttp使用Get和Post访问服务器的工具类(一)
- HttpURLConnection 访问服务器,GET和POST方法.
- HttpUrlConnection 下的post, get , 和图片下载(工具类)
- HttpUrlConnection访问服务器登录 get post
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送post和get请求
- 使用HttpURLConnection向服务器发送post和get请求
- Android使用HttpURLConnection向服务器发送post和get请求
- HttpUrlConnection的简单使用--get和post的简单使用
- 基于HttpURLConnection 的Get\Post封装(一)
- 使用HttpURLConnection发送post和get请求
- 使用HttpURLConnection发送post和get请求
- 使用HttpURLConnection发送post和get请求
- 使用HttpURLConnection发送post和get请求
- 使用HttpURLConnection发送post和get请求
- 使用HttpURLConnection发送post和get请求
- Android常见问题——找不到HttpClient和okHttp的包
- Android常见问题——Genymotion无法启动问题
- webService快速入门入门系列《6》----cfx框架集成spring
- Android使用HTTP协议访问网络——HttpClient
- 打开U盘时出现“使用驱动器 X:中的光盘之前需要将其格式化。”字样
- HttpUrlConnection使用Get和Post访问服务器的工具类(一)
- 重写了Servlet的init方法后一定要记得调用父类的init方法
- OkHttp使用Get和Post访问服务器的工具类(一)
- 为什么Android无法设置无标题栏?
- 在Fragment中加一个嵌套了ListView的ScrollView(一)
- ScrollView中嵌套ExpandableListView
- 【096】Linux CentOS 7.3 允许或禁止root用户远程登录
- Android MVC,MVP,MVVM模式入门——重构登陆注册功能
- SVN 回滚(撤回)提交的代码