1、界面

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity" > <EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:text="张三"
/> <EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword" /> <Button
android:onClick="myGetData"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陆" /> </LinearLayout>

2、MainActivity代码,用来响应button代码

 package com.example.getdata;

 import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import com.example.getdata.service.LoginService; 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 et_username;
private EditText et_password;
/*private Handler handler = new Handler(){ @Override
public void handleMessage(android.os.Message msg) {
// TODO Auto-generated method stub } };*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText)findViewById(R.id.et_username);
et_password = (EditText)findViewById(R.id.et_password);
} public void myGetData(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
System.out.println("username:" + username);
System.out.println("password:" + password);
new Thread(){
public void run(){
//final String result = LoginService.loginByGet(username, password);
//final String result = LoginService.loginByPost(username, password);
//final String result = LoginService.loginByClientGet(username, password);
final String result = LoginService.loginByClientPost(username, password);
if(result != null){
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, result, 0).show();
} });
}else{
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "请求不成功!", 0).show();
} });
}
};
}.start();
} }

3、http请求同步代码

 package com.example.getdata.service;

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
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.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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import com.example.getdata.utils.StreamTools;
/*
* 注意事项:在发送请求时,如果有中文,注意把它转换为相应的编码
*/
public class LoginService { public static String loginByGet(String username, String password){
try {
String path = "http://192.168.1.100/android/index.php?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
//conn.setRequestProperty(field, newValue);
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
String result = StreamTools.readInputStream(is);
return result;
}else{
return null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} } public static String loginByPost(String username, String password){
String path = "http://192.168.1.101/android/index.php";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
conn.setRequestProperty("Content-Length", data.length() + "");
//允许向外面写数据
conn.setDoOutput(true);
//获取输出流
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
String result = StreamTools.readInputStream(is);
return result;
}else{
System.out.println("----111");
return null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("----2222");
return null;
} } public static String loginByClientGet(String username, String password){
try{
//1、打开一个浏览器
HttpClient client = new DefaultHttpClient(); //输入地址ַ
String path = "http://192.168.1.101/android/index.php?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
HttpGet httpGet = new HttpGet(path); //敲回车
HttpResponse response = client.execute(httpGet); //获取返回状态码
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();
String result = StreamTools.readInputStream(is);
return result;
}else{
System.out.println("----111");
return null;
}
}catch(Exception e){
e.printStackTrace();
System.out.println("----222");
return null;
} } public static String loginByClientPost(String username, String password){
try {
//�������
HttpClient client = new DefaultHttpClient(); //�����ַ
String path = "http://192.168.1.101/android/index.php";
HttpPost httpPost = new HttpPost(path);
//ָ��Ҫ�ύ�����ʵ��
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username",username));
parameters.add(new BasicNameValuePair("password",password)); httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
HttpResponse response = client.execute(httpPost);
//��ȡ�������
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();
String result = StreamTools.readInputStream(is);
return result;
}else{
System.out.println("----111");
return null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("----222");
e.printStackTrace();
return null;
}
}
}

4、把输入流转换为字符串

package com.example.getdata.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; public class StreamTools {
/*
* 功能:把inputStream转化为字符串
*/
public static String readInputStream(InputStream is){
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1){
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] result = baos.toByteArray();
return new String(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} }
}

5、清单文件

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

最后:一般来说,子线程是无法改变UI的,但是这里采用runOnUiThread方式是可以的,而不是采用发送消息的方式

android http同步请求的更多相关文章

  1. Android okHttp网络请求之Get/Post请求

    前言: 之前项目中一直使用的Xutils开源框架,从xutils 2.1.5版本使用到最近的xutils 3.0,使用起来也是蛮方便的,只不过最近想着完善一下app中使用的开源框架,由于Xutils里 ...

  2. 基于Retrofit+RxJava的Android分层网络请求框架

    目前已经有不少Android客户端在使用Retrofit+RxJava实现网络请求了,相比于xUtils,Volley等网络访问框架,其具有网络访问效率高(基于OkHttp).内存占用少.代码量小以及 ...

  3. Android - 使用Volley请求网络数据

    Android - 使用Volley请求网络数据 Android L : Android Studio 14 个人使用volley的小记,简述使用方法,不涉及volley源码 准备工作 导入Volle ...

  4. Okhttp同步请求源码分析

    进阶android,OKhttp源码分析——同步请求的源码分析 OKhttp是我们经常用到的框架,作为开发者们,我们不单单要学会灵活使用,还要知道他的源码是如何设计的. 今天我们来分析一下OKhttp ...

  5. Android 使用Retrofit请求API数据

    概览 Retrofit 是一个Square开发的类型安全的REST安卓客户端请求库.这个库为网络认证.API请求以及用OkHttp发送网络请求提供了强大的框架 .理解OkHttp 的工作流程见  这个 ...

  6. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  7. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  8. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  9. Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

    前言: 通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少少有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下R ...

随机推荐

  1. 了解Linux 命名空间

    转载: http://laokaddk.blog.51cto.com/368606/674256 命名空间提供了虚拟化的一种轻量级形式,使得我们可以从不同的方面来查看运行系统的全局属性.该机制类似于S ...

  2. applet部署,无需修改客户端设置。

    1  开发applet程序,编译成jar包 2  给jar包做数字签名: (1).用keytool生成密钥: keytool -genkey -keystore myapplet.keystore - ...

  3. javascript 中 keyup、keypress和keydown事件

    keyup.keypress和keydown事件都是有关于键盘的事件 1. keydown事件在键盘的键被按下的时候触发,keyup 事件在按键被释放的时候触发    keydown.keypress ...

  4. JavaSE思维导图(五)

  5. hosts文件简析

    什么是hosts文件 hosts文件是个什么文件呢?Hosts虽然没有后缀名,其实是个纯文本文件,可以用记事本等文本编辑软件打开.Hosts文件主要用于在本地电脑强制解析域名,Hosts文件里包含映射 ...

  6. 选择器,$("A+B") 和$("A~B") 的理解

    在我发表这个理解之前,我有看过博客园 永恒浪子 大神的 JQuery选择器大全(http://www.cnblogs.com/hulang/archive/2011/01/12/1933771.htm ...

  7. prime算法求最小生成树(畅通工程再续)

    连着做了四道畅通工程的题,其实都是一个套路,转化为可以求最小生成树的形式求最小生成树即可 这道题需要注意: 1:因为满足路的长度在10到1000之间才能建路,所以不满足条件的路径长度可以初始化为无穷 ...

  8. Windows下提升进程权限(转)

    from: http://www.oschina.net/code/snippet_222150_19533 windows的每个用户登录系统后,系统会产生一个访问令牌(access token) , ...

  9. IO库 8.4

    题目:编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中. #include <iostream> #includ ...

  10. Html页面操作json串

    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaSc ...