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 ...
随机推荐
- 为Docker容器指定自定义网段的固定IP/静态IP地址
第一步:创建自定义网络 备注:这里选取了172.172.0.0网段,也可以指定其他任意空闲的网段 docker network create --subnet=172.172.0.0/16 docke ...
- lua 可变参数
问题:对可变参数传递的时候,采用如下方案: local cellData = {MsgText = msgText,Param = ...,CallBackFunc = callBackFunc,Ca ...
- TOMCAT启动时报错:the CATALINA_HOME environment variable is not defined correctly
运行tomcat/bin目录下的startup.bat时报错:the CATALINA_HOME environment variable is not defined correctly 碰到这个问 ...
- 几个常见Win32 API函数
1.获取客户区矩形区域 RECT cliRect; GetClientRect(hWnd, &cliRect); 2.获取窗口上下文句柄 HDC hdc = GetDC(hWnd);//... ...
- 使用 HTML5 input 类型提升移动端输入体验
在过去的几年里,在移动设备上浏览网页已变得难以置信的受欢迎. 但是这些设备上的浏览体验,有时遗留很多的有待改进.当涉及到填写表单时,这一点尤为明显.幸运的是,HTML5规范引入了许多新input类型, ...
- iOS cocospods Updating local specs repositories
pod install --verbose --no-repo-update (在安装的时候) pod update --verbose --no-repo-update (在更新库的时候) 如果长时 ...
- Maven-005-部署构件至 nexus 私服
nexus 私服仓库中宿主仓库主要用于储存装置内部的或一些无法从公共仓库获取的第三方构件,供项目组的人员使用.日常开发中,可将各版本构件直接部署到 Nexus 中对应策略的宿主仓库中.上篇文章中讲述了 ...
- M1卡修改各区块控制位值和数据
(一),以常用设置"08 77 8F 69"控制条件为例,先搞清楚它――具有的访问权限. 1.对"08 77 8F 69"值进行计算,该值定位于各区块3的6,7 ...
- NSMutableAttributedString 富文本的使用
//富文本的使用 UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(, , , )]; testLabel.backgroun ...
- RabbitMQ学习总结 第三篇:工作队列Work Queue
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...