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("失败");
}
}
android中的HttpURLConnection和HttpClient实现app与pc数据交互的更多相关文章
- Android中使用HttpURLConnection实现GET POST JSON数据与下载图片
Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client全部的包与类都标记为deprecated ...
- Android中获取系统上安装的APP信息
Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00003259 Android中获取系统上安装的APP信 ...
- 使用webservice实现App与服务器端数据交互
What? webservice曾经认为是解决异构系统间整合的最佳解决方案,不依赖于第三方任何系统的支持(不需要部署RDBMS服务器),大家只需要按照官方的规范,即可完成相互之间的数据交互. Why? ...
- Android中使用HTTP和HttpClient进行通信
/** * 使用HTTP的Get方式进行数据请求 */ protected void httpGet() { /** * 进行异步请求 */ new AsyncTask<String, Void ...
- [Android基础]Android中使用HttpURLConnection
HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求.POST请求.它在URLConnetion的基础上提供了例如以下便捷的方法. int getRe ...
- android中两个不同名称的app不能同时安装
---恢复内容开始--- 两个app,第一个安装后,再安装第二个,会提示安装包损坏或者一切其他问题,但是这个安装包在别的手机可以正常安装,可以是因为以下问题 两个app中,包含有相同名称的provid ...
- android 中设置HttpURLConnection 超时并判断是否超时
设置超时: URL url1 = new URL(url); HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); c ...
- android中怎么把自己须要的app启动图标集中到一个弹出框中
先看效果图 这个是我们自己的apk点击之后的效果 下边是布局文件 activity_main.xml主布局文件 <LinearLayout xmlns:android="http:// ...
- android中利用HttpURLConnection进行Get、Post和Session读取页面。
直接上代码,调用的时候要放在线程中. package slj.getsms; import java.io.BufferedReader; import java.io.InputStreamRead ...
随机推荐
- 移动端性能优化动态加载JS、CSS
JS CODE (function() { /** * update: * 1.0 */ var version = "insure 1.1.0"; var Zepto = Zep ...
- phpcms v9的url优化
nginx配置重定向 # nginx rewrite rule rewrite ^/show-(.+)-(.+)-(.+).html$ /index.php?m=content&c=index ...
- [knowledge][basic][hardware] 内存的硬件结构(转)
写的并不太易懂,但概念性的科普已足够. 原文地址:http://blog.csdn.net/miaomao1989/article/details/51508195 Memory中的Channel/R ...
- JS中构造函数与函数
//构造函数中,如果返回的是一个对 象,那么就保留原意. 如果返回的是非对象,比如数字.布尔和字符串,那么就返回 this,如果没有 return 语句,那么也返回this. var myFun1 = ...
- 命令行子shell 括号 ()
子shell 控制变量 ansible-direc:~ # (export hello=world;echo $hello)worldansible-direc:~ # echo $hello ans ...
- jQuery源代码阅读之三——jQuery实例方法和属性
jQuery实例方法及属性相关的代码结构如下 jQuery.fn=jQuery.prototype={ jQuery:core_version, constructor:jQuery, selecto ...
- Netty writeAndFlush() 流程与异步
Netty writeAndFlush()方法分为两步, 先 write 再 flush @Override public ChannelFuture writeAndFlush(Object msg ...
- opencv实现图像邻域均值滤波、中值滤波、高斯滤波
void CCVMFCView::OnBlurSmooth()//邻域均值滤波 { IplImage* in; in = workImg; IplImage* out = cvCreateImage( ...
- Leetcode: Strong Password Checker
A password is considered strong if below conditions are all met: It has at least 6 characters and at ...
- @Autowired获取被@Service注解的bean为null的问题
先说结论:Spring容器还没有加载完Bean,你就去调用了! 一般的注解没加,bean的名字写错都好检查,但是逻辑错误就需要看清自己的思维过程了. 实例:在使用ActiveMq的过程中,第一步对Ac ...