amdroid 9.2.2
修改上次的项目,在app的build.gradle里的dependencies添加compile 'com.squareup.okhttp3:okhttp:3.4.1'修改mainactivity.javapackage com.example.xinwei.networktest;
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button)findViewById(R.id.send_request);
responseText = (TextView)findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId()==R.id.send_request){
//sendRequestWithHttpURLConnection();
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
new Thread(){
@Override
public void run(){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.baidu.com").build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void sendRequestWithHttpURLConnection() {
new Thread() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader=null;
try {
URL url = new URL("http://www.fishC.com");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/x-java-serialized-object");
Log.d("MainActivity", ""+connection.getResponseCode());
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
}
}.start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
这个sendRequestWithOkHttp();函数就是用okhttp模块实现获取百度网站内容的功能。
效果图:
页:
[1]