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 内核无线子系统

    Linux 内核无线子系统 浅谈 Linux 内核无线子系统 Table of Contents 1. 全局概览 2. 模块间接口 3. 数据路径与管理路径 4. 数据包是如何被发送? 5. 谈谈管理 ...

  2. Vmware 克隆CentOS 网络IP配置

    在VMware里克隆出来的CentOS Linux.. ifconfig...没有看到eth0..然后重启网卡又报下面错误. 故障现象: service network restart Shuttin ...

  3. SQL Server 修改表

    alter table 可能用三种方式来完成. 第一种: 只修改元数据. 1.删除一个列. 2.一个行被增加而且空值被认为是所有行的新值. 3.当可变长度的列的长度增加时. 4.不允许为空的列被允许为 ...

  4. Oracle EBS-SQL (AR-2):检查应收收款核销额

    SELECT cust.customer_number, cust.customer_name, cash.receipt_number,            gcc.segment1 || '.' ...

  5. ICON图标文件解析

    icon是一种图标格式,用于系统图标.软件图标等,这种图标扩展名为*.icon.*.ico.常见的软件或windows桌面上的那些图标一般都是ICON格式的. ICON文件格式比较简单,包含文件头段. ...

  6. python手记(9)

    本博客所有内容是原创,未经书面许可,严禁任何形式的转 http://blog.csdn.net/u010255642 tab #!/usr/bin/env python # example noteb ...

  7. winds引导配置数据文件包含的os项目无效

    我装了winds7与linux双系统,用easyBcd程序时,删除了一个winds7,之后winds7就进不去了, 进入winds7时显示winds未能启动,原因可能是最近更改了硬件或软件.解决此问题 ...

  8. 解决Android中TextView首行缩进的问题

    方式一:(推荐) setText("\u3000\u3000"+xxxxx); 方式二:这种方式不同分辨率会有问题 setText(""+xxxxx); 半角: ...

  9. libcurl使用示例

    远程下载文件,并将http 头信息存放内存中以及文件大小等相关信息: #include <stdio.h> #include <curl/curl.h> #include &l ...

  10. org.openqa.selenium.SessionNotCreatedException: A new session could not be created.

    解决方案 1. 重新插拔手机. 2. 检查appium端口是否被占用,如是,杀掉占用了改端口的进程,然后重启appium. 3.