android笔记-httpurlconnection 报错 主要代码 使用okhttp

报错

调用InputStream in = connection.getErrorStream(); 报错

主要代码 使用okhttp

直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.lvc.nnetworktest.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by lvc on 2017/2/7.
* 网络请求util
* 封装了 httpURLConnection & okhttp3
*/
public class HtppUtil {
public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
//InputStream in =null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line =reader.readLine())!=null){
response.append(line);
}
if(listener != null){
listener.onFinish(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
if(listener != null){
listener.onError(e);
}
}finally {
if(connection != null){
connection.disconnect();
}
/* if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
}
}).start();
}
public interface HttpCallbackListener{
void onFinish(String response);
void onError(Exception e);
}
/**
* okhttp3
*/
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); //调用回调
}
}