使用原生的HTTPURLConnection,能说的不多,注意直接用百度的网址已经不能显示了。
public class HttpActivity extends AppCompatActivity {
private TextView httpShow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
Button httpBtn= (Button) findViewById(R.id.httpBtn);
httpShow = (TextView) findViewById(R.id.httpShow);
httpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithHttpUrlConnect();
}
});
}
private void sendRequestWithHttpUrlConnect(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection=null;
BufferedReader reader=null;
try {
URL url=new URL("https://zhidao.baidu.com/question/457099811.html");
httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode()==200) {
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
}else{
Log.d("csc","连接失败");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpURLConnection!=null){
httpURLConnection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
HttpActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
httpShow.setText(response);
}
});
}
}
使用OkHttp发送Http请求
private void sendRequestWithOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
String url="https://zhidao.baidu.com/question/457099811.html";
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(url).build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// String result=response.body().string();
String result=new String(response.body().bytes(),"GBK");//默认转换的编码格式是UTF-8,这里指定为GBK
showResponse(result);
}
});
}
}).start();
}