注意点:

1.Get和post这两种提交方式有何不同?

很明显post方式提交多了content-length和content-type这两项,所以post提交是要为这两项设置setRequestProperty属性

处理乱码问题

①客户端发送请求时没有对URL进行编码,我们只要使用URLEncoder.encode(keyValue,"UTF-8")处理即可。

②Tomcat服务器在获取参数时,默认编码不是"UTF-8",一般是"ISO-8859-1",此时要如何处理呢?

主要思路是这样的:先把以"ISO-8859-1"(假设是这种编码,如果不是也无所谓)编码获取的数据转为最原始的二进码数据,然后再对该二进制数据以"UTF-8"格式进行重新编码

1.在一个web项目中创建一个servlet。让android项目访问servlet的路径,返回结果

loginServlet.java

package cn.com.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//服务器接受统一编码iso-8859-1,然后获取字符串时转化为utf-8

String name = new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");

String password = request.getParameter("password");

System.out.println("name:"+name);

System.out.println("password:"+password);

if(name.equals("张三")&&password.equals("123")){

//往浏览器写字符串

response.getOutputStream().write("get方式登录成功".getBytes("utf-8")); //写到浏览器的编码是utf-8

}

else{

response.getOutputStream().write("get方式登录失败".getBytes("utf-8")); //写到浏览器的编码是utf-8

}

}

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//doGet(request, response);

//服务器接受统一编码iso-8859-1,然后获取字符串时转化为utf-8

String name = new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");

String password = request.getParameter("password");

System.out.println("name:"+name);

System.out.println("password:"+password);

if(name.equals("张三")&&password.equals("123")){

//往浏览器写字符串

response.getOutputStream().write("post方式登录成功".getBytes("utf-8")); //写到浏览器的编码是utf-8

}

else{

response.getOutputStream().write("post方式登录失败".getBytes("utf-8")); //写到浏览器的编码是utf-8

}

}

}

2.android项目

(1)添加网络访问权限

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

(2)布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<EditText

android:id="@+id/name"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="输入用户名"

android:text="张三"

/>

<EditText

android:id="@+id/password"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="输入密码" />

<Button

android:id="@+id/button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="get提交"

android:onClick="onClick1"

/>

<Button

android:id="@+id/button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="post提交"

android:onClick="onClick2"

/>

</LinearLayout>

MainActivity.java

package com.example.get;

import java.io.UnsupportedEncodingException;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends Activity {

private EditText name,password;

private final int SUCCESS=1;

private Handler handler = new Handler(){

@Override

public void handleMessage(Message msg) {

if(msg.what==SUCCESS){

String result = (String) msg.obj;

if(result!=null){

).show();

}else{

Toast.makeText(MainActivity.this, "登陆失败", 1).show();

}

}

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

name = (EditText) findViewById(R.id.name);

password = (EditText) findViewById(R.id.password);

}

/**

* get方式提交

* @param view

*/

public void onClick1(View view){

final String loginName = name.getText().toString();

final String loginPasswor = password.getText().toString();

new Thread(){

@Override

public void run() {

String result = null;

try {

result = LoginService.loginByGet(loginName, loginPasswor);

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Message msg = new Message();

msg.what=SUCCESS;

msg.obj=result;

handler.sendMessage(msg);

}

}.start();

}

/**

* post方式提交

* @param view

*/

public void onClick2(View view){

final String loginName = name.getText().toString();

final String loginPasswor = password.getText().toString();

new Thread(){

@Override

public void run() {

final String result=LoginService.loginByPost(loginName, loginPasswor);

if(result!=null){

//在主线程上运行

runOnUiThread(new Runnable() {

@Override

public void run() {

Toast.makeText(MainActivity.this, result, 1).show();

}

});

}

}

}.start();

}

}

3.业务类

LoginService .java

package com.example.get;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

public class LoginService {

public static String loginByGet(String name,String password) throws UnsupportedEncodingException{

//拼路径

String getpath = "http://10.162.0.171:8080/WebGet/LoginServlet?name="+URLEncoder.encode(name,"utf-8")+"&password="+URLEncoder.encode(password,"utf-8");//提交是得utf-8

String result = null;

int code;

try {

URL url = new URL(getpath);

//根据url发送http请求

HttpURLConnection conn=(HttpURLConnection) url.openConnection();

//发送提交方式

conn.setRequestMethod("GET");

//设置连接时间

conn.setConnectTimeout(5000);

//获取服务器返回码

code = conn.getResponseCode();

if(code==200){

InputStream is = conn.getInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len=0;

if((len=is.read(buffer))!=-1){

baos.write(buffer, 0, len);

}

is.close();

baos.close();

byte[] b=baos.toByteArray();

String s = new String(b);

result=s;

}else{

System.out.println(code);

result="";

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

result="";

}

return result;

}

public static String loginByPost(String name,String password){

String postpath = "http://10.162.0.171:8080/WebGet/LoginServlet";

String result = null;

int code;

try {

URL url = new URL(postpath);

HttpURLConnection conn=(HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

conn.setConnectTimeout(5000);

//name="+name+"&password="+password

//准备数据

String data ="name="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(password, "utf-8");//提交是得utf-8

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

conn.setRequestProperty("Content-Length", data.length()+"");

//post 方式实际上是浏览器把数据写个服务器

conn.setDoOutput(true);//true 可以写出数据

OutputStream os=conn.getOutputStream();

os.write(data.getBytes());

code = conn.getResponseCode();

if(code==200){

InputStream is = conn.getInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len=0;

if((len=is.read(buffer))!=-1){

baos.write(buffer, 0, len);

}

is.close();

baos.close();

byte[] b=baos.toByteArray();

String s = new String(b);

result=s;

}else{

System.out.println(code);

result="";

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

result="";

}

return result;

}

}

http-使用get和post方式提交数据的更多相关文章

  1. Android 采用post方式提交数据到服务器

    接着上篇<Android 采用get方式提交数据到服务器>,本文来实现采用post方式提交数据到服务器 首先对比一下get方式和post方式: 修改布局: <LinearLayout ...

  2. Android(java)学习笔记213:开源框架post和get方式提交数据(qq登录案例)

    1.前面提到Http的get/post方式  . HttpClient方式,实际工作的时候不常用到,因为这些方式编写代码是很麻烦的 2.Android应用会经常使用http协议进行传输,网上会有很完善 ...

  3. Android 使用Post方式提交数据(登录)

    在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持. 在HTTP通信中使用最多的就是GET和POS ...

  4. Android 使用Post方式提交数据

    在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持. 在HTTP通信中使用最多的就是GET和POS ...

  5. 苹果微信浏览器不能post方式提交数据问题

    form表单中采用post方式提交数据时,在苹果的微信浏览器中无法传递,安卓的可以 如图: 在controller中获取该数据为 null 将表单的提交方式修改为get就能够获取到 现在采用Ajax方 ...

  6. Android(java)学习笔记156:开源框架post和get方式提交数据(qq登录案例)

    1. 前面提到Http的get/post方式  . HttpClient方式,实际工作的时候不常用到,因为这些方式编写代码是很麻烦的 2. Android应用会经常使用http协议进行传输,网上会有很 ...

  7. postman 中post方式提交数据

    post方式提交数据时,把参数填写在body中而不是pOST下面的哪一行

  8. Android 采用get方式提交数据到服务器

    首先搭建模拟web 服务器,新建动态web项目,servlet代码如下: package com.wuyudong.web; import java.io.IOException; import ja ...

  9. JQuery以JSON方式提交数据到服务端

    JQuery将Ajax数据请求进行了封装,从而使得该操作实现起来容易许多.以往我们要写很多的代码来实现该功能,现在只需要调用$.ajax()方法,并指明请求的方式.地址.数据类型,以及回调方法等.下面 ...

  10. easyui form 方式提交数据

    http://ldzyz007.iteye.com/blog/2067540 <form id="ff" method="post">      . ...

随机推荐

  1. 【转】使用git、git-flow与gitlab工作

    转自:http://www.tuicool.com/articles/BZJRj2 使用git.git-flow与gitlab工作 时间 2013-11-02 00:40:39  Axb的自我修养 原 ...

  2. String的类型的数据

    字符串类型的数据也是计算机基础. var box = "lc"; var box1 = 'lc1'; //不管是单引号还双引号,都必须成对出现 1.ECMAscript规定字符串是 ...

  3. zabbix监控MySQL

    通过使用mysql_performance_monitor软件包实现zabbix对mysql的监控. 1.安装依赖软件.yum install perl-File-Which perl-libwww- ...

  4. Centos php项目发布问题

    LAMP环境,项目运行错误日志路径:/var/log/httpd 错误日志例如: [Sat Jul :: ] [error] [client , referer: http://192.168.100 ...

  5. Vue.2.0.5-表单控件绑定

    基础用法 你可以用 v-model 指令在表单控件元素上创建双向数据绑定.它会根据控件类型自动选取正确的方法来更新元素.尽管有些神奇,但 v-model 本质上不过是语法糖,它负责监听用户的输入事件以 ...

  6. TCP/IP之TCP的建立与终止

    TCP协议简介 tcp/ip协议族中传输层最重要的两种协议是UDP和TCP协议,上一篇文章用很短的篇幅介绍完了UDP协议相关的内容,但相对于UDP而言的TCP协议,是种更复杂,应用更广的协议.在接下来 ...

  7. pip是用国内镜像源

    pipy国内镜像目前有: http://pypi.douban.com/  豆瓣 http://pypi.hustunique.com/  华中理工大学 http://pypi.sdutlinux.o ...

  8. 续【C# 以管理员方式启动Winform,进而使用管理员控制Windows Service】

    前提:在我们的域环境下,给分配了管理员级别两个账号(user0,user1). 需求:只允许一个账户运行进程"WindowsFormsApplication1": 1,)当已经运行 ...

  9. zabbix监控企业esxi虚拟机

    zabbix监控企业esxi虚拟机 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我来公司有一段时间了,最近也发现模型部有测试和开发反应某台机器登陆不上去了,结果登陆esxi服务器 ...

  10. IOS 设备参数

    Iphone,Ipad,ITouch 各个型号参数对比