您的位置:首页 > 理论基础 > 计算机网络

Android之Http协议编程04-HttpURLConnection

2014-08-19 23:09 218 查看
不知不觉已经好几个月没有写过博客,感觉有点生疏了,好了废话不多说今天接上次的博客Http第四篇,上次数据到服务端。今天要讲的是以java接口也就是HttpURLConnection来上传数据到服务端,其中数据是以附在访问路径后面来做的。经常上网同学或者做过J2EE的人应该碰到到类似这样的访问路径:Http://192.168.1.102/XX/XX.?
username=admin&pwd = 123的路径,没错这就是我们把数据提交到服务器的一种方式。这种方式的提交有两种get和post方式,只是它们的区别大家自行查找资料,这里就不多讲。

今天我就带大家小案例,这个案例是简单模仿登陆功能,案例包括简单写个web服务端和Android客服端,这里先讲下这个项目的主要是怎么样的,这个项目首先在Android客服端上两个空格让你填入用户名和密码,我们单击一个按钮就把数据提交到了服务器上了,当然服务器上就会得到这两个数据,简单做下判断,当然为了结合前面所讲的,我们这里把数据回传给客服端,当登陆成功在客服端上显示login
is success当登陆失败,客服端上显示login is error。.

首先,我们要建立一个web工程,简单建立一个Servlet来作为服务端,代码如下:



GetDataServlet.java

package com.kun.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class GetDataServlet extendsHttpServlet {

/**

* The doGet method of the servlet. <br>

*

* This method is called when a form has itstag value method equals to get.

*

* @param request the request send by theclient to the server

* @param response the response send by theserver to the client

* @throws ServletException if an erroroccurred

* @throws IOException if an error occurred

*/

publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

response.setContentType("text/html;charset=utf-8");

PrintWriterout = response.getWriter();

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

StringuserName = request.getParameter("username");

Stringpassword = request.getParameter("pwd");;

if("kun".equals(userName)&&"123".equals(password)){

out.println("loginis success");//回传数据给Android客服端

System.out.println("loginis success!!!");//方面测试,在控制台上打印

}else{

out.println("loginis error");

System.out.println("loginis error!!!");

}

out.flush();

out.close();

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has itstag value method equals to post.

*

* @param request the request send by theclient to the server

* @param response the response send by theserver to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

this.doGet(request,response);

}

}

访问地址:

http://192.168.1.102:8080/HttpSubmitDataDoGet/GetDataServlet?username=kun&pwd=123

这里的ip是我电脑的ip

运行结果:



好了服务端我们已经搭建好了,现在开始写客服端代码,因为时间关系,我就不贴出一步步的步骤,只贴出代码来,代码里我会写出注释,相信大家看的懂:

Xml

main.xml

<?xml
version="1.0"encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>

<LinearLayout

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="用户名:"
/>
<EditText
android:id="@+id/username"

android:layout_width="fill_parent"
android:layout_height="50dp"
android:hint="请输入用户名"
/>
</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="密
码:"
/>
<EditText

android:id="@+id/pwd"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:hint="请输入密码"
/>
</LinearLayout>
<Button

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登陆"
android:onClick="buttonClick"
/>
<TextView
android:id="@+id/result"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</LinearLayout>

Http04Activity.java

package your.kun.http;

import java.util.HashMap;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

public class Http04Activity extends Activity {

/**Called when the activity is first created. */

privateString path ="http://192.168.1.102:8080/HttpSubmitDataDoGet/GetDataServlet";

privateEditText username;

privateEditText pwd;

privateTextView result;

@Override

publicvoid onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

init();

}

/**

* 初始化

*/

privatevoid init() {

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

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

result= (TextView) findViewById(R.id.result);

}

/**

* 点击登陆事件

*

* @param view

*/

publicvoid buttonClick(View view) {

HashMap<String,String> data = getData();

Stringstr = HttpUtils.submitData(path, data);

if(str!= null){

result.setText(str);

}

}

/**

* 将要上传的数据封装到HashMap里

* @return

*/

privateHashMap<String, String> getData() {

HashMap<String,String> data = new HashMap<String, String>();

StringuserName = username.getText().toString().trim();

StringpassWord = pwd.getText().toString().trim();

data.put("username",userName);

data.put("pwd",passWord);

returndata;

}

}

//封装好的Http工具

HttpUtils.java

package your.kun.http;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Map;

public class HttpUtils {

/**

* get方式提交数据

* @param path

* @param data

* @return

*/

publicstatic String submitData(String path,HashMap<String, String> data){

Stringresult = null;

try{

StringBufferbuffer = new StringBuffer(path);

buffer.append("?");

for(Map.Entry<String,String> entry:data.entrySet()){

buffer.append(entry.getKey()).append("=").append(entry.getValue());

buffer.append("&");

}

//删掉最后一个&

buffer.deleteCharAt(buffer.length()-1);

Stringsb = buffer.toString().trim();

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

URLurl = new URL(sb);

HttpURLConnectionconnection = (HttpURLConnection)url.openConnection();

connection.setConnectTimeout(5* 1000);

connection.setRequestMethod("GET");

connection.setDoInput(true);

connection.setDoOutput(true);

intreponseCode = connection.getResponseCode();

if(200== reponseCode){//success

InputStreaminputStream = connection.getInputStream();//得到输入流

result= parseInputStream(inputStream);

}

}catch (Exception e) {

e.printStackTrace();

}

returnresult;

}

/**

* 解析流得到字符串

* @param inputStream

* @return

*/

privatestatic String parseInputStream(InputStream inputStream) {

Stringresult = null;

ByteArrayOutputStreamarrayOutputStream = new ByteArrayOutputStream();

try{

byte[]buffer = new byte[1024];

intlen = 0;

while((len = inputStream.read(buffer)) != -1) {

arrayOutputStream.write(buffer,0, len);

}

result= new String(arrayOutputStream.toByteArray());

}catch (IOException e) {

e.printStackTrace();

}finally{

closeStream(inputStream,arrayOutputStream);

}

returnresult;

}

/**

* 关闭流

* @param inputStream

* @param arrayOutputStream

*/

privatestatic void closeStream(InputStream inputStream,

ByteArrayOutputStreamarrayOutputStream) {

if(null!= inputStream){

try{

inputStream.close();

}catch (IOException e) {

e.printStackTrace();

}

}

if(null!= arrayOutputStream){

try{

arrayOutputStream.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

}

不要忘了权限:

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

最终效果图:





Ps:这个是在2.2系统做的,所以网络访问在ui里不会报错,不过3.0系统以上访问网络就报错:android.os.NetworkOnMainThreadException,意思就是不能在主线程访问网络(因为访问网络是一项耗时工作),这时我们就应该另取一条线程来访问网络。下次讲解使用Apache接口来实现文本数据的上传。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: