HttpURLConnection
protected void getHttp(final String path) {
// TODO Auto-generated method stub
new Thread() {
public void run() {
try {
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setConnectTimeout(5000);
openConnection.setReadTimeout(5000);
int responseCode = openConnection.getResponseCode();
if (responseCode == 200) {
// 获取响应的输入流对象
InputStream is = openConnection.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
String msg = new String(message.toByteArray());
Log.e("tag","获取到的数据为:"+msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
;
}.start();
}
Retrofit
public Retrofit getRetrofit(){
if(build == null){
//关闭自动重连
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.retryOnConnectionFailure(false);
//设置66秒超时
OkHttpClient client = builder.
connectTimeout(66, TimeUnit.SECONDS).
readTimeout(66, TimeUnit.SECONDS).
writeTimeout(66, TimeUnit.SECONDS).build();
//创建接口IP连接
build = new Retrofit.Builder()
.client(client).baseUrl(ApiConstants.URL_FREE)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return build;
}
调用
Call<ResponseBody> responseBodyCall = getRetrofit().create(MainService.class).queryFree_Stream();
responseBodyCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
网友评论