您的位置:首页 > 理论基础 > 计算机网络

Android 网络通讯之HTTP请求通信

2016-09-23 23:02 337 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。

Android网络通讯平台支持还是比较丰富的,除了兼容J2ME中的java.netapi外还提供了一下Android平台独有的类android.net这个Package。一种是GET方式,一种是POST方式。然后HttpClient的Get/Post方式。似乎更强大的是org.apache.http类,这个是apache实验室开源的包,对于Http请求处理很方便。

android 向web服务器发送post请求并获取结果,因为 需要访问到网络必须要有权限,先在AndroidManifest.xml中加入如下配置:

[java]
view plain
copy

print?

<uses-permission android:name="android.permission.INTERNET"/>    



<uses-permission android:name="android.permission.INTERNET"/>


1.发送post请求并获取结果的activity 代码如下(结果返回1(成功)或-1(失败0)):

[java]
view plain
copy

print?

btnOK.setOnClickListener(new OnClickListener(){    
        
@Override    
public void onClick(View view) {    
    String url="http://192.168.123.7:8900/Login.aspx";    
    HttpPost httpRequest=null;    
    List<NameValuePair> params=null;    
    HttpResponse httpResponse=null;    
    //建立HttpPost链接    
    httpRequest=new HttpPost(url);    
    //Post操作参数必须使用NameValuePair[]阵列储存    
    params=new ArrayList<NameValuePair>();    
    params.add(new BasicNameValuePair("domain",domain.getText().toString()));    
    params.add(new BasicNameValuePair("uid",uid.getText().toString()));    
    params.add(new BasicNameValuePair("pwd",pwd.getText().toString()));    
        
    try    
    {       
        //发送Http Request    
        httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));    
        //取得Http Response    
        httpResponse=new DefaultHttpClient().execute(httpRequest);    
        //若状态码为200    
        if(httpResponse.getStatusLine().getStatusCode()==200)    
        {    
            //获得返回的数据    
            String strResult=EntityUtils.toString(httpResponse.getEntity());    
             if(strResult.equalsIgnoreCase("1"))    
             {    
                // openDialog("登入成功!");    
                new AlertDialog.Builder(Login.this)    
                .setTitle("提示").setMessage("登入成功!")    
                .setPositiveButton("确定",new DialogInterface.OnClickListener() {    
                    @Override    
                    public void onClick(DialogInterface arg0, int arg1) {    
                        // 跳转到另一个Acitivity并传值    
                        Intent intent=new Intent();    
                        intent.putExtra("curUserId",domain.getText().toString()+"/"+ uid.getText().toString());    
                        intent.setClass(Login.this, Holiday.class);    
                        Login.this.startActivity(intent);    
                    }    
                }).show();     
             }    
             else if(strResult.equalsIgnoreCase("0"))    
             {    
                 openDialog("您输入的信息有误!");    
             }    
        }    
        else    
        {    
            openDialog("Error!");    
            }    
    }    
    catch(Exception e)    
    {    
        e.printStackTrace();    
    }    
}});    



btnOK.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View view) {
String url="http://192.168.123.7:8900/Login.aspx";
HttpPost httpRequest=null;
List<NameValuePair> params=null;
HttpResponse httpResponse=null;
//建立HttpPost链接
httpRequest=new HttpPost(url);
//Post操作参数必须使用NameValuePair[]阵列储存
params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("domain",domain.getText().toString()));
params.add(new BasicNameValuePair("uid",uid.getText().toString()));
params.add(new BasicNameValuePair("pwd",pwd.getText().toString()));

try
{
//发送Http Request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//取得Http Response
httpResponse=new DefaultHttpClient().execute(httpRequest);
//若状态码为200
if(httpResponse.getStatusLine().getStatusCode()==200)
{
//获得返回的数据
String strResult=EntityUtils.toString(httpResponse.getEntity());
if(strResult.equalsIgnoreCase("1"))
{
// openDialog("登入成功!");
new AlertDialog.Builder(Login.this)
.setTitle("提示").setMessage("登入成功!")
.setPositiveButton("确定",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 跳转到另一个Acitivity并传值
Intent intent=new Intent();
intent.putExtra("curUserId",domain.getText().toString()+"/"+ uid.getText().toString());
intent.setClass(Login.this, Holiday.class);
Login.this.startActivity(intent);
}
}).show();
}
else if(strResult.equalsIgnoreCase("0"))
{
openDialog("您输入的信息有误!");
}
}
else
{
openDialog("Error!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}});
2.HttpClient的Get方式发送请求到服务器

[java]
view plain
copy

print?

String url = "XXXXXXX";  
HttpClient httpClient = new DefaultHttpClient();  
//创建HttpGet对象  
HttpGet httpGet = new HttpGet(url);  
HttpResponse httpResponse;  
try  
{  
    //使用execute方法发送 HttpGet请求,并返回httRresponse对象  
    httpResponse = httpClient.execute(httpGet);  
    int statusCode = httpResponse.getStatusLine().getStatusCode();  
    if(statusCode==HttpStatus.SC_OK)  
    {  
        //获得返回结果  
        response=EntityUtils.toString(httpResponse.getEntity());  
    }  
                  
} catch (ClientProtocolException e)  
{             
    e.printStackTrace();  
} catch (IOException e)  
{             
    e.printStackTrace();  
}  
return response;  



String url = "XXXXXXX";
HttpClient httpClient = new DefaultHttpClient();
//创建HttpGet对象
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try
{
//使用execute方法发送 HttpGet请求,并返回httRresponse对象
httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK)
{
//获得返回结果
response=EntityUtils.toString(httpResponse.getEntity());
}

} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return response;

一,GET方式

[java]
view plain
copy

print?

public class Activity01 extends Activity {  
   
 private final String DEBUG_TAG = "System.out";  
   
 private TextView mTextView ;  
 private Button mButton;  
   
 protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.http);  
    
  mTextView = (TextView)findViewById(R.id.TextView01);  
  mButton = (Button)findViewById(R.id.Button01);  
  mButton.setOnClickListener(new httpListener());  
 }  
   
 //设置按钮监听器  
 class httpListener implements OnClickListener{  
  public void onClick(View v) {  
   refresh();  
  }  
 }  
  
 private void refresh(){  
  String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";  
  //URL可以加参数  
  //String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";  
  String resultData = "";  
  URL url = null;  
  try{  
   //创建一个URL对象  
   url = new URL(httpUrl);  
  }catch(MalformedURLException e){  
   Log.d(DEBUG_TAG, "create URL Exception");  
  }  
  //声明HttpURLConnection对象  
  HttpURLConnection urlConn = null;  
  //声明InputStreamReader对象  
  InputStreamReader in = null;  
  //声明BufferedReader对象  
  BufferedReader buffer = null;  
  String inputLine = null;  
  if(url != null){  
   try{  
    //使用HttpURLConnection打开连接  
    urlConn = (HttpURLConnection) url.openConnection();  
    //得到读取的内容(流)  
    in = new InputStreamReader(urlConn.getInputStream());  
    //创建BufferReader对象,输出时候用到  
    buffer = new BufferedReader(in);  
    //使用循环来读取数据  
    while ((inputLine = buffer.readLine()) != null) {  
     //在每一行后面加上换行  
     resultData += inputLine + "\n";  
    }  
    //设置显示取的的内容  
    if(resultData != null && !resultData.equals("")){  
     mTextView.setText(resultData);  
    }else{  
     mTextView.setText("读取的内容为空");  
    }  
   }catch(IOException e){  
    e.printStackTrace();  
   }finally{  
    try {  
     //关闭InputStreamReader  
     in.close();  
     //关闭URL连接  
     urlConn.disconnect();  
    } catch (IOException e) {  
     e.printStackTrace();  
    }  
   }  
  }else{  
   Log.d(DEBUG_TAG, "URL is NULL");  
  }  
 }  
}  



public class Activity01 extends Activity {

private final String DEBUG_TAG = "System.out";

private TextView mTextView ;
private Button mButton;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);

mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}

//设置按钮监听器
class httpListener implements OnClickListener{
public void onClick(View v) {
refresh();
}
}

private void refresh(){
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
//URL可以加参数
//String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
String resultData = "";
URL url = null;
try{
//创建一个URL对象
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.d(DEBUG_TAG, "create URL Exception");
}
//声明HttpURLConnection对象
HttpURLConnection urlConn = null;
//声明InputStreamReader对象
InputStreamReader in = null;
//声明BufferedReader对象
BufferedReader buffer = null;
String inputLine = null;
if(url != null){
try{
//使用HttpURLConnection打开连接
urlConn = (HttpURLConnection) url.openConnection();
//得到读取的内容(流)
in = new InputStreamReader(urlConn.getInputStream());
//创建BufferReader对象,输出时候用到
buffer = new BufferedReader(in);
//使用循环来读取数据
while ((inputLine = buffer.readLine()) != null) {
//在每一行后面加上换行
resultData += inputLine + "\n";
}
//设置显示取的的内容
if(resultData != null && !resultData.equals("")){
mTextView.setText(resultData);
}else{
mTextView.setText("读取的内容为空");
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
//关闭InputStreamReader
in.close();
//关闭URL连接
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Log.d(DEBUG_TAG, "URL is NULL");
}
}
}
二,POST方式

[java]
view plain
copy

print?

public class Activity03 extends Activity {  
   
 private final String DEBUG_TAG = "System.out";  
   
 private TextView mTextView ;  
 private Button mButton;  
   
 protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.http);  
    
  mTextView = (TextView)findViewById(R.id.TextView01);  
  mButton = (Button)findViewById(R.id.Button01);  
  mButton.setOnClickListener(new httpListener());  
 }  
   
 //设置按钮监听器  
 class httpListener implements OnClickListener{  
  public void onClick(View v) {  
   refresh();  
  }  
 }  
   
 private void refresh(){  
  String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";  
  String resultData = "";  
  URL url = null;  
  try{  
   //创建一个URL对象  
   url = new URL(httpUrl);  
  }catch(MalformedURLException e){  
   Log.d(DEBUG_TAG, "create URL Exception");  
  }  
  //声明HttpURLConnection对象  
  HttpURLConnection urlConn = null;  
  //声明InputStreamReader对象  
  InputStreamReader in = null;  
  //声明BufferedReader对象  
  BufferedReader buffer = null;  
  String inputLine = null;  
  //声明DataOutputStream流  
  DataOutputStream out = null;  
  if(url != null){  
   try{  
    //使用HttpURLConnection打开连接  
    urlConn = (HttpURLConnection) url.openConnection();  
    //因为这个是POST请求所以要设置为true  
    urlConn.setDoInput(true);  
    urlConn.setDoOutput(true);  
    //设置POST方式  
    urlConn.setRequestMethod("POST");  
    //POST请求不能设置缓存  
    urlConn.setUseCaches(false);  
    urlConn.setInstanceFollowRedirects(false);  
    //配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
    //连接,从postUrl.openConnection()至此的配置必须要在connect之前完成  
    //要注意的是connectio.getOutputStream会隐含的进行connect  
    urlConn.connect();  
    //DataOutputStream流  
    out = new DataOutputStream(urlConn.getOutputStream());  
    String content = "par=" + URLEncoder.encode("abcdefg","gb2312");  
    //将要上传的内容写入流中  
    out.writeBytes(content);  
    //得到读取的内容(流)  
    in = new InputStreamReader(urlConn.getInputStream());  
    //创建BufferReader对象,输出时候用到  
    buffer = new BufferedReader(in);  
    //使用循环来读取数据  
    while ((inputLine = buffer.readLine()) != null) {  
     //在每一行后面加上换行  
     resultData += inputLine + "\n";  
    }  
    //设置显示取的的内容  
    if(resultData != null && !resultData.equals("")){  
     mTextView.setText(resultData);  
    }else{  
     mTextView.setText("读取的内容为空");  
    }  
   }catch(IOException e){  
    e.printStackTrace();  
   }finally{  
    try {  
     //刷新DataOutputStream流  
     out.flush();  
     //关闭DataOutputStream流  
     out.close();  
       
     //关闭InputStreamReader  
     in.close();  
     //关闭URL连接  
     urlConn.disconnect();  
    } catch (IOException e) {  
     e.printStackTrace();  
    }  
   }  
  }else{  
   Log.d(DEBUG_TAG, "URL is NULL");  
  }  
 }  
}  



public class Activity03 extends Activity {

private final String DEBUG_TAG = "System.out";

private TextView mTextView ;
private Button mButton;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);

mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}

//设置按钮监听器
class httpListener implements OnClickListener{
public void onClick(View v) {
refresh();
}
}

private void refresh(){
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
String resultData = "";
URL url = null;
try{
//创建一个URL对象
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.d(DEBUG_TAG, "create URL Exception");
}
//声明HttpURLConnection对象
HttpURLConnection urlConn = null;
//声明InputStreamReader对象
InputStreamReader in = null;
//声明BufferedReader对象
BufferedReader buffer = null;
String inputLine = null;
//声明DataOutputStream流
DataOutputStream out = null;
if(url != null){
try{
//使用HttpURLConnection打开连接
urlConn = (HttpURLConnection) url.openConnection();
//因为这个是POST请求所以要设置为true
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
//设置POST方式
urlConn.setRequestMethod("POST");
//POST请求不能设置缓存
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(false);
//配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接,从postUrl.openConnection()至此的配置必须要在connect之前完成
//要注意的是connectio.getOutputStream会隐含的进行connect
urlConn.connect();
//DataOutputStream流
out = new DataOutputStream(urlConn.getOutputStream());
String content = "par=" + URLEncoder.encode("abcdefg","gb2312");
//将要上传的内容写入流中
out.writeBytes(content);
//得到读取的内容(流)
in = new InputStreamReader(urlConn.getInputStream());
//创建BufferReader对象,输出时候用到
buffer = new BufferedReader(in);
//使用循环来读取数据
while ((inputLine = buffer.readLine()) != null) {
//在每一行后面加上换行
resultData += inputLine + "\n";
}
//设置显示取的的内容
if(resultData != null && !resultData.equals("")){
mTextView.setText(resultData);
}else{
mTextView.setText("读取的内容为空");
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
//刷新DataOutputStream流
out.flush();
//关闭DataOutputStream流
out.close();

//关闭InputStreamReader
in.close();
//关闭URL连接
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Log.d(DEBUG_TAG, "URL is NULL");
}
}
}
三,HttpClient的Get方式

[java]
view plain
copy

print?

public class Activity04 extends Activity {  
  
 private TextView mTextView ;  
 private Button mButton;  
   
 protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.http);  
  mTextView = (TextView)findViewById(R.id.TextView01);  
  mButton = (Button)findViewById(R.id.Button01);  
  mButton.setOnClickListener(new httpListener());  
 }  
   
 //设置按钮监听器  
 class httpListener implements OnClickListener{  
  public void onClick(View v) {  
   String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";  
   //HttpGet连接对象  
   HttpGet httpRequest = new HttpGet(httpUrl);  
   try{  
    //取的HttpClient对象  
    HttpClient httpclient = new DefaultHttpClient();  
    //请求HttpClient,取的HttpResponse  
    HttpResponse httpResponse = httpclient.execute(httpRequest);  
    //请求成功  
    if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
     //取的返回的字符串  
     String strResult = EntityUtils.toString(httpResponse.getEntity()); //这个返回值可能会在行尾出现小方格  
     //在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。  
     String strsResult = strResult.replace("\r", "");  
     mTextView.setText(strsResult);  
    }else{  
     mTextView.setText("请求错误");  
    }  
   }catch(ClientProtocolException e){  
    mTextView.setText(e.getMessage().toString());  
   }catch(IOException e){  
    mTextView.setText(e.getMessage().toString());  
   }catch(Exception e){  
    mTextView.setText(e.getMessage().toString());  
   }  
  }  
 }  
}  



public class Activity04 extends Activity {

private TextView mTextView ;
private Button mButton;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}

//设置按钮监听器
class httpListener implements OnClickListener{
public void onClick(View v) {
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";
//HttpGet连接对象
HttpGet httpRequest = new HttpGet(httpUrl);
try{
//取的HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
//请求HttpClient,取的HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取的返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity()); //这个返回值可能会在行尾出现小方格
//在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
String strsResult = strResult.replace("\r", "");
mTextView.setText(strsResult);
}else{
mTextView.setText("请求错误");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
}
}
}
四,HttpClient的POST方式

[java]
view plain
copy

print?

public class Activity05 extends Activity {  
   
 private TextView mTextView ;  
 private Button mButton;  
  
 protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.http);  
  mTextView = (TextView)findViewById(R.id.TextView01);  
  mButton = (Button)findViewById(R.id.Button01);  
  mButton.setOnClickListener(new httpListener());  
 }  
   
 //设置按钮监听器  
 class httpListener implements OnClickListener{  
  public void onClick(View arg0) {  
   String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";  
   //创建HttpPost连接对象  
   HttpPost httpRequest = new HttpPost(httpUrl);  
   //使用NameValuePair来保存要传递的Post参数  
   List<NameValuePair> params = new ArrayList<NameValuePair>();  
   //添加要传递的参数  
   params.add(new BasicNameValuePair("par","HttpClient_android_Post"));  
   try{  
    //设置字符集  
    HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");  
    //请求httpRequest  
    httpRequest.setEntity(httpentity);  
    //取的默认的HttpClient  
    HttpClient httpclient = new DefaultHttpClient();  
    //取的HttpResponse  
    HttpResponse httpResponse = httpclient.execute(httpRequest);  
    //HttpStatus.SC_OK表示连接成功  
    if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
     //取的返回的字符串  
     String strResult = EntityUtils.toString(httpResponse.getEntity());//这个返回值可能会在行尾出现小方格  
     //在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。  
     String strsResult = strResult.replace("\r", "");  
     mTextView.setText(strsResult);  
    }else{  
     mTextView.setText("请求错误");  
    }  
   }catch(ClientProtocolException e){  
    mTextView.setText(e.getMessage().toString());  
   }catch(IOException e){  
    mTextView.setText(e.getMessage().toString());  
   }catch(Exception e){  
    mTextView.setText(e.getMessage().toString());  
   }  
  }  
 }  
}  



public class Activity05 extends Activity {

private TextView mTextView ;
private Button mButton;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}

//设置按钮监听器
class httpListener implements OnClickListener{
public void onClick(View arg0) {
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
//创建HttpPost连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加要传递的参数
params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
try{
//设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
//请求httpRequest
httpRequest.setEntity(httpentity);
//取的默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//取的HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示连接成功
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取的返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());//这个返回值可能会在行尾出现小方格
//在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
String strsResult = strResult.replace("\r", "");
mTextView.setText(strsResult);
}else{
mTextView.setText("请求错误");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息