有两种方法分别是 HttpURLConnection 和HttpClient
使用HttpURLConnection
xml界面代码:
<span style="font-size:14px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.networktest.MainActivity"
android:orientation="vertical"
>
<Button
android:id="@+id/send_request"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Send Request"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/respose_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout></span>
MainActivity中的代码:
<span style="font-size:14px;">package com.example.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private TextView tv_response;
protected static final int SHOW_RESPONSE = 0;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
tv_response.setText(response);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_response = (TextView) findViewById(R.id.respose_text);
Button btn_send = (Button) findViewById(R.id.send_request);
btn_send.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
//开启线程发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try{
URL url = new URL("http://192.168.1.101/AndroidLogin/servlet/LoginServlet?userName=dumas&passWord=1213");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);
//对获取到的输入流进行读取
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn!=null){
conn.disconnect();
}
}
}
}).start();
}
}</span>注意还要添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
以上是使用GET提交的,假如使用POST则如下:
<span style="font-size:14px;">private void sendRequestWithHttpURLConnection() {
//开启线程发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try{
URL url = new URL("http://192.168.1.101/AndroidLogin/servlet/LoginServlet");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);
//---向服务器提交姓名和密码
DataOutputStream daos = new DataOutputStream(conn.getOutputStream());
daos.writeBytes("userName=duams&passWord=123");
//对获取到的输入流进行读取
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
response.append(line);
}
</span>使用HttpClient
是用Get方式提交数据
<span style="font-size:14px;">public void run() {
HttpURLConnection conn = null;
try{
//使用Get方式提交数据
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://192.168.1.101/AndroidLogin/servlet/LoginServlet?userName=dumas&passWord=123"<span style="white-space: pre; "> </span>);
HttpResponse httpReponse = httpClient.execute(httpGet);
if(httpReponse.getStatusLine().getStatusCode()==200){
HttpEntity entity = httpReponse.getEntity();
response = EntityUtils.toString(entity,"utf-8");
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn!=null){
conn.disconnect();
}
}
}
}).start();
}</span>使用POST方式提交
private void sendRequestWithHttpURLConnection() {
//开启线程发起网络请求
new Thread(new Runnable() {
private String response;
@Override
public void run() {
HttpURLConnection conn = null;
try{
//使用Get方式提交数据
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.101/AndroidLogin/servlet/LoginServlet");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", "dumas"));
params.add(new BasicNameValuePair("passWord", "123"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity, "utf-8");
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn!=null){
conn.disconnect();
}
}
}
}).start();
}
原文地址:http://blog.csdn.net/qq_20042935/article/details/43564595