前几天,由于开发需求,研究了一下各种HTTP发送post,get方法,封装成工具类,记录一下,供后续用到方便查看。

package com.fh.loginauth.util;import android.content.Context;
import android.util.Log;
import android.widget.Toast;import com.fh.loginauth.HttpCallbackListener;
import com.fh.loginauth.MainActivity;
import com.fh.loginauth.MyCallback;
import com.zhy.http.okhttp.OkHttpUtils;import org.json.JSONException;
import org.json.JSONObject;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;import javax.net.ssl.HttpsURLConnection;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class HttpUtil {private static String urlAddress = "http://10.96.156.89:6060/aaa/index.jsp";/*** 发送HTTP请求* @param address 地址* @param listener 回调*/public static void sendHttpRequest(final String address, finalHttpCallbackListener listener) {new Thread(new Runnable() {@Overridepublic void run() {//               HttpsURLConnection connection = null;HttpURLConnection connection = null;try {URL url = new URL(address);//                   connection = (HttpsURLConnection) url.openConnection();connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");//设置请求报文头,设定请求数据类型
//                    connection.setRequestProperty("Content-Type",
//                            "application/json");connection.setConnectTimeout(8000);connection.setReadTimeout(8000);connection.setDoInput(true);connection.setDoOutput(true);InputStream in = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}if (listener != null) {//回调onFinish()方法listener.onFinish(response.toString());}} catch (Exception e) {if (listener != null) {listener.onError(e);}} finally {if (connection != null) {connection.disconnect();}}}}).start();}/*** 发送Http post请求* @param urlAddress*/public static void sendRequestWithHttpURLConnection(final String urlAddress){new Thread(new Runnable() {@Overridepublic void run() {HttpURLConnection connection = null;BufferedReader reader = null;try {URL url = new URL(urlAddress);connection = (HttpURLConnection) url.openConnection();
//                    connection.setRequestMethod("GET");//发送POST请求connection.setRequestMethod("POST");//设置请求报文头,设定请求数据类型connection.setRequestProperty("Content-Type","application/json");DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.writeBytes("identity=C84029B714D2");connection.setConnectTimeout(8000);connection.setReadTimeout(8000);InputStream in = connection.getInputStream();//对获取到的地输入流进行读取reader = new BufferedReader(new InputStreamReader(in));StringBuilder responses = new StringBuilder();String line;while ((line = reader.readLine())!= null){responses.append(line);}Log.d("HttpUtil", "--responses--"+responses.toString());} catch (Exception e) {e.printStackTrace();}finally {if ( reader != null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}if (connection != null){connection.disconnect();}}}}).start();}/*** 发送OK HTTP请求* @param address* @param callback*/public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(address).build();client.newCall(request).enqueue(callback);}//doGetpublic static void doGet(String s) {final String getUrl = urlAddress + s;new Thread(new Runnable() {@Overridepublic void run() {try {URL url = new URL(getUrl);try {HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.connect();if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {InputStream inputStream = httpURLConnection.getInputStream();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));StringBuffer stringBuffer = new StringBuffer();String readLine = "";while ((readLine = bufferedReader.readLine()) != null) {stringBuffer.append(readLine);}inputStream.close();bufferedReader.close();httpURLConnection.disconnect();Log.d("TAG", stringBuffer.toString());} else {Log.d("TAG", "fail");Log.d("TAG", "---httpURLConnection.getResponseCode()-----"+httpURLConnection.getResponseCode());}} catch (IOException e) {e.printStackTrace();}} catch (MalformedURLException e) {e.printStackTrace();}}}).start();}/*** 以OK HTTP发送post请求* @param url* @param object*/public void postString(String url, JSONObject object) {
//        JSONObject map = new JSONObject();
//        try {
//            map.put("identity", "C84029B714D2");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }OkHttpUtils.postString().url(url).content(object.toString()).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new MyCallback());}/*** 获取post请求的结果,注意此为耗时操作*/public static void sendPostOkHttpRequest(String address, JSONObject object, okhttp3.Callback callback) {try {OkHttpClient client = new OkHttpClient();MediaType mediaType = MediaType.parse("application/json");String requestBody = object.toString();Request request = new Request.Builder().url(address).post(RequestBody.create(mediaType, requestBody)).build();client.newCall(request).enqueue(callback);}catch (Exception e){e.printStackTrace();}}private void doPost(){OkHttpClient client = new OkHttpClient.Builder().build();Request request = new Request.Builder().url("http://10.96.156.89:6060/aaa/services/rest/V2/AAA/AutoConfig").post(RequestBody.create(MediaType.parse("application/json"), "aaa".getBytes())).build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.d("HttpUtil", "------"+e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d("HttpUtil", "---res>>---"+response.body().string());String resData = response.body().string();try {Toast.makeText(MyApplication.getContext(), "---onResponse Success---",       Toast.LENGTH_LONG).show();}catch (Exception e){e.printStackTrace();}}});}}

Android发送网络请求(post,get)工具类相关推荐

  1. android发送网络请求没反应,Android无法使用HttpURLConnection发送GET请求

    我正在尝试在我的应用程序中使用HttpURLConnection.我将我的请求方法设置为'GET',但是当我尝试检索输出流时,该方法将更改为'POST'! 我不确定是什么原因,但是当我使用'POST' ...

  2. Android 通过WebService进行网络编程,使用工具类轻松实现

    转帖请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/17483273),请尊重他人的辛勤劳动成果,谢谢! 相信大家 ...

  3. OkHttp3 发送网络请求服务器

    前言:应用程序需要发送网络请求服务器的接口,可使用OkHttp 3发送请求获取服务端数据 GitHut地址 Step 1:申请网络请求的权限:在manifests层的AndroidManifest.x ...

  4. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  5. 【小王的安卓之路】Android原生网络请求

    Android原生网络请求 一. 网络请求的必要性 二. 网络请求分类 三. 网络请求实现方法 四. 注意事项 一.网络请求的必要性: 如今单机APP早已经接近消失就连最简单的时钟日期等软件都需要去请 ...

  6. 网络编程-JavaScript中发送网络请求汇总

    文章目录 1.前后端分离优势 2.HTTP协议的解析 2.1 HTTP的介绍 2.2 HTTP的组成 2.3 HTTP的版本 2.4 HTTP请求方式 2.5 HTTP请求头字段 2.6 HTTP响应 ...

  7. Android PermissionUtils:运行时权限工具类及申请权限的正确姿势

    Android PermissionUtils:运行时权限工具类及申请权限的正确姿势 ifadai 关注 2017.06.16 16:22* 字数 318 阅读 3637评论 1喜欢 6 Permis ...

  8. android之网络请求 -- 获取RecyclerView的列表项(图片 + 文字)

    android之网络请求 -- 获取RecyclerView的列表项 示意图,网络请求的地址,插件及依赖 代码架构 代码内容 MainActivity.java activity_main.xml R ...

  9. 微信小程序中发送网络请求

    文章目录 小程序项目 app.json pages/index/index.html pages/index/index.wxss pages/index/index.js 发送网络请求 网络请求函数 ...

  10. 利用Fiddler对Android手机网络请求进行抓包

    在Android的开发调试过程中,特别是针对网络编程的情况,很多时候我们希望能够对Android的网络请求进行抓包,用来定位以及分析我们程序的问题.下面我介绍使用Fiddler对Android模拟器的 ...

最新文章

  1. 【连载】物联网全栈教程-从云端到设备(十三)---安装单片机编译环境
  2. ASP.NET Master Page
  3. cannot open file mfc42u.lib的问题解决
  4. 讲一下Asp.net core MVC2.1 里面的 ApiControllerAttribute
  5. python的pyqt5_Pycharm+Python+PyQt5使用详解
  6. 的pcie带宽_新品推荐:乐扩PCIe四路SDI高清采集卡
  7. 网关gateway解决跨域问题
  8. 远程分支显示不全 idea_IDEA中的Git操作,看完你就会了
  9. 给你出道题:依次去掉离中心最远的M个点
  10. java单例模式之深入浅出
  11. mysql 四种隔离级别
  12. AX 2012导入Demo数据
  13. css003 选择器:明确设置哪些样式
  14. roboware studio教程_2.2.RoboWare Studio安装及使用
  15. 如何保存PPT的背景图片
  16. 2017-2018-2 20179306 《网络攻防技术》第八周作业
  17. 煮一壶清茶,悟一种人生
  18. Apollo安装记录
  19. 欧奈尔的RPS指标如何使用到股票预测
  20. greenplum-执行SQL创建SliceGang 学习计划。

热门文章

  1. 计算机文化基础(高职高专版 第十一版)第七章 答案
  2. 【J2ME笔记】关于J2ME Image图片指定颜色透明化
  3. 中铁置业引入USB Server助力RPA机器人
  4. Java完成excel表格导出
  5. java修改桌面背景_用Java更换Windows桌面壁纸
  6. 计算机中心pdca,信息中心日常运维工作PDCA持续改进.docx
  7. ESP32烧录Arduino生成的bin文件
  8. 操作系统 | Linux基础教程
  9. 利用Maven构建appfuse。
  10. 网络流量监测IP雷达 1.0