http通过get、post方式传参数给服务器
1.先在myeclipse中新建服务器
新建MyServlet文件
<span style="font-size:14px;">package com.base.module;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("G_UserName");
String age = request.getParameter("G_UserPassword");
response.setContentType("text/html;charset=utf-8");
//获得输出流
PrintWriter out = response.getWriter();
//打印接收到的数据
out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age);
System.out.print("name=" +new String(name.getBytes("ISO-8859-1"),"utf-8"));
System.out.print(" age=" + age);
}
}</span>
新建jsp文件,里面放置form表单
<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
<form action = "/MyWebProject/MyServlet" method = "get">
name:<input type= "text" name="name"><br/>
age:<input type="text" name ="age"><br/>
submit:<input type = "submit" value="submit"><br/>
</form>
</body>
</html></span>
服务器端完成,接下来写客户端程序!
客户端的功能,类似于注册,有文本框输入用户名,密码,点击提交按钮,提交注册信息。
xml文件
<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/rl">
<TextView
android:id="@+id/name"
android:text="name:"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/name_editText"
android:layout_below="@id/name"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl">
<TextView
android:id="@+id/age_textView"
android:text="age:"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_below="@id/age_textView"
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/age_editText"
/>
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="register"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout></span><strong>
</strong>
MainActivity文件:
package com.example.rr;
import android.app.Activity;
import android.os.Handler;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText name;
private EditText age;
private Button button;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
name = (EditText)findViewById(R.id.name_editText);
age = (EditText)findViewById(R.id.age_editText);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String URL = "http://192.168.1.107:8080/MyWebProject/MyServlet";
new HttpConnection(URL,name.getText().toString(),age.getText().toString()).start();
}
});
}
}
HttpConnection文件
package com.example.rr;
import android.os.Handler;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
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.Properties;
/**
* Created by xiaoyuer on 2015/11/13.
*/
public class HttpConnection extends Thread{
private String mUrl;
private Handler mHandler;
private String name;
private String age;
HttpConnection(String Url,String name,String age)
{
this.mUrl = Url;
this.name = name;
this.age = age;
}
private void doGet(){
//doget方式发送中文信息一定要转码,用encode方法
try{
mUrl = mUrl +"?name=" + URLEncoder.encode(name,"utf-8")+"&age=" + age;
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
try {
//构建url对象
URL httpUrl = new URL(mUrl);
//通过openConnection方法打开一个HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
//设置请求超时,访问网页时可能没给我们应答,设置超时等待时间
conn.setReadTimeout(5000);
//设置访问请求方式
conn.setRequestMethod("GET");
//做一个包装类,封装信息,把输入流(InputStreamReader)转换成字节流(BufferedReader)
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while((str = reader.readLine()) != null){
sb.append(str);
}
System.out.println("result:"+sb.toString());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public void doPost()
{
try {
//得到操作系统的默认配置信息
Properties property = System.getProperties();
property.list(System.out);
//构建url对象
URL httpUrl = new URL(mUrl);
//通过openConnection方法打开一个HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
//设置请求超时,访问网页时可能没给我们应答,设置超时等待时间
conn.setReadTimeout(5000);
//设置访问请求方式
conn.setRequestMethod("POST");
//获得输出流
OutputStream out = conn.getOutputStream();
//post方法发送的数据先封装成实体
String content = "name=" + name +"&age" + age;
//通过out.write()方式发送给后台,getBytes()方法将数据转换为字节流
out.write(content.getBytes());
//做一个包装类,封装信息,把输入流(InputStreamReader)转换成字节流(BufferedReader)
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while((str = reader.readLine()) != null){
sb.append(str);
}
System.out.println("result:"+sb.toString());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void run()
{
doGet();
}
}
解决乱码问题:
接到客户端发送的数据之后要对字符编码做处理,否则发送客户端发送中文时会产生乱码问题:解决方法:
out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age);先通过.getBytes("ISO-8859-1"),方式转换为字节,再通过utf-8格式进行转码
关键代码如下:
String name = request.getParameter("name");
String age = request.getParameter("age");
response.setContentType("text/html;charset=utf-8");
//设置文本类型,否则会出现乱码
//获得输出流
PrintWriter out = response.getWriter();
//打印接收到的数据
out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age); //转码,否则会出现乱码
System.out.print("name=" +new String(name.getBytes("ISO-8859-1"),"utf-8"));
System.out.print(" age=" + age);