自学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("失败");
}
}

android中的HttpURLConnection和HttpClient实现app与pc数据交互的更多相关文章

  1. Android中使用HttpURLConnection实现GET POST JSON数据与下载图片

    Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client全部的包与类都标记为deprecated ...

  2. Android中获取系统上安装的APP信息

    Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00003259 Android中获取系统上安装的APP信 ...

  3. 使用webservice实现App与服务器端数据交互

    What? webservice曾经认为是解决异构系统间整合的最佳解决方案,不依赖于第三方任何系统的支持(不需要部署RDBMS服务器),大家只需要按照官方的规范,即可完成相互之间的数据交互. Why? ...

  4. Android中使用HTTP和HttpClient进行通信

    /** * 使用HTTP的Get方式进行数据请求 */ protected void httpGet() { /** * 进行异步请求 */ new AsyncTask<String, Void ...

  5. [Android基础]Android中使用HttpURLConnection

    HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求.POST请求.它在URLConnetion的基础上提供了例如以下便捷的方法. int getRe ...

  6. android中两个不同名称的app不能同时安装

    ---恢复内容开始--- 两个app,第一个安装后,再安装第二个,会提示安装包损坏或者一切其他问题,但是这个安装包在别的手机可以正常安装,可以是因为以下问题 两个app中,包含有相同名称的provid ...

  7. android 中设置HttpURLConnection 超时并判断是否超时

    设置超时: URL url1 = new URL(url); HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); c ...

  8. android中怎么把自己须要的app启动图标集中到一个弹出框中

    先看效果图 这个是我们自己的apk点击之后的效果 下边是布局文件 activity_main.xml主布局文件 <LinearLayout xmlns:android="http:// ...

  9. android中利用HttpURLConnection进行Get、Post和Session读取页面。

    直接上代码,调用的时候要放在线程中. package slj.getsms; import java.io.BufferedReader; import java.io.InputStreamRead ...

随机推荐

  1. ExtJS笔记 Store

    The Store class encapsulates a client side cache of Model objects. Stores load data via a Proxy, and ...

  2. symmetric multiprocessor

    https://en.wikipedia.org/wiki/Symmetric_multiprocessor_system A symmetric multiprocessor system (SMP ...

  3. The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character.

    http://dev.mysql.com/doc/refman/5.7/en/index-btree-hash.html MySQL 5.7 Reference Manual  /  ...  /   ...

  4. haproxy log config

    Step 4: Configuring logging Edit /etc/sysconfig/syslog SYSLOGD_OPTIONS=”-m 0 -r”   ————————————————— ...

  5. IUS

    后端提取的sdf中可能是有negative timing 在interconnect上的,可能的原因是crosstalk之类的问题导致. negative timing在FF,clock的delay超 ...

  6. 报表控件NCReport教程:集成NCReport到Qt应用程序中

    NCReport是一款轻量级.快速.多平台.简单易用的基于Qt toolkit的C++编写的报表解决方案,目前主要包括报表渲染库和报表设计器GUI应用程序. 但是好多使用NCReport控件的朋友都不 ...

  7. Linux 中断详解 【转】

    转自:http://blog.csdn.net/tiangwan2011/article/details/7891818 原文地址 http://www.yesky.com/20010813/1921 ...

  8. Css Study - 横向MENU

    http://cssmenumaker.com/menu/tabbed-chrome-and-blue HTML <div id="topMenu"> <ul&g ...

  9. php将抓取的图片链接下载到本地

    备注: fclose这一步操作完成之后如果返回值是空表示下载成功,否则会返回1或者其他错误提示 这个步骤测试的时候实在yii2框架的基础上执行的,下载到的图片实在frontend目录下的web目录下( ...

  10. Ubuntu 16.04 标题栏实时显示上下行网速、CPU及内存使用率--indicator-sysmonitor

    ---------------------------------------------------------------------------- 原文地址:http://blog.csdn.N ...