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. Confluent

    Confluent介绍(一)   最开始接触confluent是通过这篇博客,How to Build a Scalable ETL Pipeline with Kafka Connect,对于做大数 ...

  2. Python进阶--GUI编程

    一.图形用户图面(GUI编程) 1. wxpython下载和安装: 下载url: http://wxpython.org/download.php 2.创建示例GUI应用程序 : ①开始需要导入wx ...

  3. android开源框架和开源项目(转)

    特效: http://www.androidviews.net/ http://www.theultimateandroidlibrary.com/ 常用效果: 1. https://github.c ...

  4. JAVA 中的RMI是什么

    RMI的概念 RMI(Remote Method Invocation)远程方法调用是一种计算机之间利用远程对象互相调用实现双方通讯的一种通讯机制.使用这种机制,某一台计算机上的对象可以调用另外 一台 ...

  5. The Suspects(并查集求节点数)

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 28164   Accepted: 13718 De ...

  6. [置顶] Guava学习之Splitter

    Splitter:在Guava官方的解释为:Extracts non-overlapping substrings from an input string, typically by recogni ...

  7. android部分控件应用解析

    java中的接口回调机制图解 1. Adapter 接口概述   Adapter是一个顶层列表视图和底层数据的桥梁,通过adapter可以获取列表视图中所体现的数据条目,并且通过adapter可以为数 ...

  8. c# 第三方控件 闪退

    使用了第三方控件之后 出现了闪退的情况!  该第三方控件的软件没有注册或没有安装改第三方控件的软件

  9. Android自定义View和控件之一-定制属于自己的UI

    照例,拿来主义.我的学习是基于下面的三篇blog.前两是基本的流程,第三篇里有比较细致的绘制相关的属性.第4篇介绍了如何减少布局层次来提高效率. 1. 教你搞定Android自定义View 2. 教你 ...

  10. 我的学习笔记之API-Guides翻译------AppComponent_Activites

    10.26第一天开始:贵在坚持,边看遍整理 一个应用程序通常由多个Activity组成,它们之间是松耦合的关系.特别的,有一个Activity作为app的主Activity,当app首次启动时呈现给用 ...