码迷,mamicode.com
首页 > Web开发 > 详细

HttpURLConnection——get,post

时间:2016-04-12 22:27:10      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

package com.ch.day4_httpurlconn;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private TextView jsonData;
private Button login;
//服务器地址,路径
public static final String JSON_URL = "http://169.254.109.73:8080/tqyb/newsList.json";
public static final String LOGIN_URL = "http://169.254.109.73:8080/serverof1407a/loginServlet";

//定义一个handler的匿名内部类的对象
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 1){
jsonData.setText((String)msg.obj);
}else if(msg.what == 2){
login.setText((String)msg.obj);
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();
}

public void init(){
jsonData = (TextView) findViewById(R.id.jsonData);
login = (Button) findViewById(R.id.login);
//点击login到服务器登陆验证
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//在次线程中,请求web服务器
new Thread(){
public void run() {
//调用httpurlconnection的get请求,到服务器请求json数据
// String rs = loginByServerByGet("admin", "123456");

String rs = loginByServerByPost("admin1", "123456");
//在此次线程中,通过handler把数据传递给主线程,显示在主线程的组件中
handler.sendMessage(handler.obtainMessage(2, rs));
if("success".equals(rs)){
//跳转到功能页面,
}else{
//提示登录失败,请修改登录信息等等
}

};
}.start();
}
});

jsonData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//在次线程中,请求web服务器
new Thread(){
public void run() {
//调用httpurlconnection的get请求,到服务器请求json数据
String rs = getJsonFromWeb();//此方法请求web服务器
//在此次线程中,通过handler把数据传递给主线程,显示在主线程的组件中
handler.sendMessage(handler.obtainMessage(1, rs));
};
}.start();
}
});
}
//到服务器验证登陆信息,,通过post请求
public String loginByServerByPost(String name,String pass){
String rs = "";
URL url = null;
HttpURLConnection urlConn = null;
BufferedReader br = null;
DataOutputStream output = null;
// StringBuffer sb = new StringBuffer();//定义缓存字符串,拼装字符串
try {

url = new URL(LOGIN_URL);//创建和服务器的连接对象URL
urlConn = (HttpURLConnection) url.openConnection();//打开连接
urlConn.setConnectTimeout(5*1000);//设置连接超时容忍时间
urlConn.setReadTimeout(5*1000);//设置读取时间

//设置post请求
urlConn.setRequestMethod("POST");
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
//通过post请求,向服务器传值
output = new DataOutputStream(urlConn.getOutputStream());//创建服务器的输出流
String data = "username="+name+"&userpass="+pass;
output.write(data.getBytes());
output.flush();
output.close();//传值成功,完毕

if(urlConn.getResponseCode() == 200){//如果响应码为200表示响应成功,并且同时成功的相应了数据
//获得服务器相应的数据,字节输入流(数据流),转换为缓存字符流便于读取
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"utf-8"));
rs = br.readLine();//获得服务器返回的简单数据
System.out.println(rs);
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return rs;//转换为字符串,返回
}
//到服务器验证登陆信息,,通过get请求
public String loginByServerByGet(String name,String pass){
String rs = "";
URL url = null;
HttpURLConnection urlConn = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer(LOGIN_URL);//定义缓存字符串,拼装字符串
try {
sb.append("?username="+name);
sb.append("&userpass="+pass);
System.out.println(sb.toString());
url = new URL(sb.toString());//创建和服务器的连接对象URL
urlConn = (HttpURLConnection) url.openConnection();//打开连接
urlConn.setConnectTimeout(5*1000);//设置连接超时容忍时间
urlConn.setReadTimeout(5*1000);//设置读取时间
if(urlConn.getResponseCode() == 200){//如果响应码为200表示响应成功,并且同时成功的相应了数据
//获得服务器相应的数据,字节输入流(数据流),转换为缓存字符流便于读取
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"utf-8"));
rs = br.readLine();//获得服务器返回的简单数据
System.out.println(rs);
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return rs;//转换为字符串,返回
}


public String getJsonFromWeb(){
URL url = null;
HttpURLConnection urlConn = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();//定义缓存字符串,拼装字符串
try {
url = new URL(JSON_URL);//创建和服务器的连接对象URL
urlConn = (HttpURLConnection) url.openConnection();//打开连接
urlConn.setConnectTimeout(5*1000);//设置连接超时容忍时间
urlConn.setReadTimeout(5*1000);//设置读取时间
if(urlConn.getResponseCode() == 200){//如果相应码为200表示响应成功,并且同时成功的相应了数据
//获得服务器相应的数据,字节输入流(数据流),转换为缓存字符流便于读取
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"utf-8"));
String str = null;
while((str = br.readLine()) != null){//一行行的读取,一行行的收集
sb.append(str);
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return sb.toString();//转换为字符串,返回
}

}

 
   

HttpURLConnection——get,post

标签:

原文地址:http://www.cnblogs.com/nanze/p/5384502.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!