您的位置:首页 > 理论基础 > 计算机网络

okhttp传输封装的工具类

2016-08-18 09:23 567 查看
package tools;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

public class HttpUtil {

/**
* 通过HttpConnection  的   Get方式获取信息

* @param path
*            请求地址
* @return byte[]
*/
public static byte[] getResult(String path) {
HttpURLConnection conn = null;

ByteArrayOutputStream baos = null;

InputStream is = null;
try {
// 1, 得到URL对象
URL url = new URL(path);

// 2, 根据URL对象打开HttpUrlConnection对象
conn = (HttpURLConnection) url.openConnection();

// 3, 设置请求方式(可以不写, 默认"GET",可以指定"POST",必须大写 )
conn.setRequestMethod("GET");
// 连接
conn.connect();

baos = new ByteArrayOutputStream();

// 4, 获取响应
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);
}

return baos.toByteArray();
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();// 断开连接
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return null;
}

/**
* 通过HttpConnection  的   Get方式获取信息
* @param path
* @return String
*/
public static String getResultStr(String path)
{
HttpURLConnection conn = null;
InputStream is =null;
BufferedReader br = null;
String str = null;
try {

URL url = new URL(path);

conn = (HttpURLConnection) url.openConnection();

if(conn.getResponseCode()==200)
{
is = conn.getInputStream();

br = new BufferedReader(new InputStreamReader(is));

str = br.readLine();

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null)
{
conn.disconnect();
}
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br!=null)
{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return str;
}

/**
* 通过HttpUrlConnection 的 post方式提交数据 , 获取响应的信息

* @param path  路径
* @param data  参数     "useName=abc&usePwd=123"  没有?
* @return String 
*/
public static String postData(String path,String data)
{
String str = null;
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;

try {
URL url = new URL(path);

conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("POST");

conn.setDoOutput(true);

os = conn.getOutputStream();
os.write(data.getBytes());
os.flush();

if(conn.getResponseCode() == 200)
{
is = conn.getInputStream();

br = new BufferedReader(new InputStreamReader(is));

str = br.readLine();

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(conn!=null)
{
conn.disconnect();
}
if(os!=null)
{
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
if(br!=null)
{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

return str;
}

/**
* 通过okHttp获取数据

* @param path
* @return byte[]
*/
public static byte[] getByteResultByOkHttp(String path)
{
byte[] data= null;

try
{

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(path).build();

// 请求数据,得到响应信息
Response response = client.newCall(request).execute();

if (response.isSuccessful()) {

data = response.body().bytes();

return data;
}

}catch(Exception exception)
{
exception.printStackTrace();
}

return data;
}

/**
*  通过okHttp获取数据
* @param path
* @return String
*/
public static String getStringResultByOkHttp(String path)
{
String data= null;

try
{

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(path).build();

// 请求数据,得到响应信息
Response response = client.newCall(request).execute();

if (response.isSuccessful()) {

data = response.body().string();

return data;
}

}catch(Exception exception)
{
exception.printStackTrace();
}

return data;
}

/**
* 通过okHttp下载图片, 接口回调的方式返回下载的结果
* @param path
* @param callBack
*/
public static void getContentByOkhttp(final String path,final DownloadCallBack callBack) {
// 耗时操作
new Thread(

new Runnable() {

public void run() {

try {

// 得到OkHttpClient
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(path).build();

// 请求数据,得到响应信息
Response response = client.newCall(request).execute();

if (response.isSuccessful()) {
byte[] data = response.body().bytes();

//通过接口回调,将数据返回给调用者
callBack.load(data);
}

} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: