java中用HTTPURLConnection与HttpClient来连接服务器。在android中同样适用。
现在我们先来讲一下HttpUrlConnection。
HttpUrlConnection同样分为doGet方法和doPost方法,我们先讲doGet方法。doPost方法与java中一样
网络连接是一个耗时操作,要将他放在一个非UI线程中去,可以用异步线程AsyncTask或者Handler
步骤:
1.先建一个Url,里边放置服务器地址
2.openConnection得到一个URLConnection
3.然后通过得到的URLConnection来获得一个输入流,用来读取服务器返回来的数据。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mBtnConnect;
private TextView mTextViewConnect;
private static final int URL_CONNECT = 0x325;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case URL_CONNECT:
String connect = (String) msg.obj;
mTextViewConnect.setText(connect);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnConnect = (Button) findViewById(R.id.button_connect);
mTextViewConnect = (TextView) findViewById(R.id.textview_connect);
mBtnConnect.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_connect:
ConnectSeverletThread thread = new ConnectSeverletThread();
thread.start();
break;
}
}
private void connectSeverlet() {
try {
// URL url = new URL("http://192.168.115.1:8080/HTTpTest_Servelet/ServeletTest");
// URL url = new URL("http://192.168.0.30:8080/MyWebTest/MyTestServelet");
URL url = new URL("http://www.360.com");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
StringBuffer buffer = new StringBuffer();
while (line!=null){
Log.d("Connect",line);
buffer.append(line);
line = br.readLine();
}
Message msg = handler.obtainMessage();
msg.what = URL_CONNECT;
msg.obj = buffer.toString().trim();//trim 省略前边和后边的空格
handler.sendMessage(msg);
br.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class ConnectSeverletThread extends Thread{
@Override
public void run() {
connectSeverlet();
}
}
}