首页 > 代码库 > android中的HttpURLConnection和HttpClient实现app与pc数据交互

android中的HttpURLConnection和HttpClient实现app与pc数据交互

   自学android的这几天很辛苦,但是很满足,因为每当学到一点点知识点都会觉得很开心,觉得今天是特别有意义的,可能这个就是一种莫名的热爱吧。

 下面来说说今天学习的HttpURLConnection和HttpClient的区别吧,其实这2种都能进行客户端和服务器的数据交互,只是HttpClient封装的更完全。

   先看下案例吧

 第一种HttpURLConnection访问服务器:

 客服端代码:

  

package com.example.demo01;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.os.StrictMode;import android.util.Log;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;@SuppressLint("NewApi")public class MainActivity extends Activity {    private EditText unameTxt, pwdTxt;    private Button loginBtn;    private static String serverPath = "http://tplovejava.xicp.net/uploadApp/HttpTestServlet";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                 //手机安装能访问        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()               .detectDiskReads()               .detectDiskWrites()               .detectNetwork()   // or .detectAll() for all detectable problems               .penaltyLog()               .build());                       //手机安装能访问        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()                       .detectLeakedSqlLiteObjects()                    .penaltyLog()                       .penaltyDeath()                       .build());          setContentView(R.layout.activity_main);        unameTxt = (EditText) findViewById(R.id.user);        pwdTxt = (EditText) findViewById(R.id.pasd);        loginBtn = (Button) findViewById(R.id.submit);        loginBtn.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                String uname = unameTxt.getText().toString();                String pwd = pwdTxt.getText().toString();                //HttpURLConnection处理服务端与客户端交互                try {                    URL url = new URL(serverPath);                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                                        //设置输入                    conn.setDoInput(true);                                        //设置输出                    conn.setDoOutput(true);                                        //设置缓存                    conn.setUseCaches(false);                                        //设置POST                    conn.setRequestMethod("POST");                    OutputStream os = conn.getOutputStream();                    PrintWriter pw = new PrintWriter(os, true);                    pw.println(1245);                                                            //返回响应 成功200                    int responseCode = conn.getResponseCode();                    System.out.print(responseCode);                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                            }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    public String dealEncode(String str){        String encode = "";        try {            encode = URLEncoder.encode(str, "utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return encode;    }}        

 

第二种 HttpClient

HttpClient client = new DefaultHttpClient();                try {                    //设置参数集合                    List<NameValuePair> params = new ArrayList<NameValuePair>();                    params.add(new BasicNameValuePair("uname", uname));                    params.add(new BasicNameValuePair("pwd", pwd));                                        //post连接                    HttpPost httpPost = new HttpPost(serverPath);                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));                    HttpResponse response = client.execute(httpPost);                                        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                        String str = EntityUtils.toString(response.getEntity(), "utf-8");                        Log.i("info", str);                    }                } catch (ClientProtocolException e) {                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }

 

服务器:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        response.setCharacterEncoding("utf-8");        PrintWriter pw = response.getWriter();        String uname = request.getParameter("uname");        String pwd = request.getParameter("pwd");        /*InputStream is = request.getInputStream();        InputStreamReader isr = new InputStreamReader(is);        BufferedReader br = new BufferedReader(isr);        System.out.println(br.readLine());*/        if("zs".equals(uname) && "123".equals(pwd)){            pw.print("成功");        }else{            pw.print("失败");        }    }