1、activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.getserverdata.MainActivity" > <EditText
android:id="@+id/et_username"
android:hint="请输入用户名"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText> <EditText
android:id="@+id/et_password"
android:hint="请输入密码"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" /> <Button
android:onClick="click1"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="get方式登录" /> <Button
android:onClick="click2"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="post方式登录" /> </LinearLayout>

2.AndroidManifest.xml 配置权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getserverdata"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>

3.get和post请求

package com.example.getserverdata.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; import com.example.getserverdata.utils.StreamUtil; public class LoginService { public static String loginByGet(String username,String password)
{ String path = "http://192.168.1.100:8088/Login.ashx?username="+username+"&password="+password; try {
//创建URL
URL url = new URL(path); //创建http连接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置连接时间
conn.setConnectTimeout(5000);
//设置请求方式
conn.setRequestMethod("GET"); //获取请求码
int code = conn.getResponseCode(); System.out.println("code:"+code); if(code==200)
{
//请求成功
//获取响应数据
InputStream is = conn.getInputStream();
//得到响应数据
String result = StreamUtil.readInputStream(is); return result;
}
else
{
//请求失败
return null;
} } catch (Exception e) {
e.printStackTrace();
} return null;
} public static String loginByPost(String username,String password)
{ String path = "http://192.168.1.100:8088/Login.ashx"; try {
//创建URL
URL url = new URL(path); //创建http连接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置连接时间
conn.setConnectTimeout(5000);
//设置请求方式
conn.setRequestMethod("POST"); //准备数据
String data = "username="+username+"&password="+password;
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Lenght", data.length()+""); //post方式 实际上是浏览器把数据写给了服务器
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes()); //获取请求码
int code = conn.getResponseCode(); System.out.println("code:"+code); if(code==200)
{
//请求成功
//获取响应数据
InputStream is = conn.getInputStream();
//得到响应数据
String result = StreamUtil.readInputStream(is); return result;
}
else
{
//请求失败
return null;
} } catch (Exception e) {
e.printStackTrace();
} return null;
}
}

4.将InputStream转为String

package com.example.getserverdata.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; public class StreamUtil { public static String readInputStream(InputStream is)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = is.read(data))!=-1)
baos.write(data, 0, len);
is.close();
baos.close();
return new String(baos.toByteArray()); } catch (Exception e) { e.printStackTrace();
} return null;
}
}

5.MainActivity

package com.example.getserverdata;

import com.example.getserverdata.service.LoginService;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends ActionBarActivity { private EditText et_username;
private EditText et_password; @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 click1(View view)
{ final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim(); new Thread(){ public void run(){ final String result = LoginService.loginByGet(username, password); System.out.println("reuslt:"+result); if(result!=null)
{
runOnUiThread(new Runnable(){ @Override
public void run() { Toast.makeText(MainActivity.this, result, 0).show();
} }); } else
{
runOnUiThread(new Runnable(){ @Override
public void run() {
Toast.makeText(MainActivity.this, "获取数据失败", 0).show();
}
}); } } }.start(); } public void click2(View view)
{ final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim(); new Thread(){ public void run(){ final String result = LoginService.loginByPost(username, password); System.out.println("reuslt:"+result); if(result!=null)
{
runOnUiThread(new Runnable(){ @Override
public void run() { Toast.makeText(MainActivity.this, result, 0).show();
} }); } else
{
runOnUiThread(new Runnable(){ @Override
public void run() {
Toast.makeText(MainActivity.this, "获取数据失败", 0).show();
}
}); } } }.start(); } }

android 使用get和post将数据提交到服务器的更多相关文章

  1. android HttpClient将数据提交到服务器

    1.HttpClient 使用方式 public static String loginByClientGet(String username,String password) { try { //打 ...

  2. 利用asynchttpclient开源项目来把数据提交给服务器

    可以通过github去查找asynchttpclient,并下载源代码,并加载到自己的工程中. 1.利用get方法提交 2.利用post方法来提交

  3. Android提交数据到JavaWeb服务器实现登录

    之前学习Android提交数据到php服务器没有成功,在看了两三个星期的视频之后,现在终于实现了与服务器的交互.虽然完成的不是PHP端的,但是在这个过程还是学到了不少东西的.现在我先来展示一下我的成果 ...

  4. Android编程中的5种数据存储方式

    Android编程中的5种数据存储方式 作者:牛奶.不加糖 字体:[增加 减小] 类型:转载 时间:2015-12-03我要评论 这篇文章主要介绍了Android编程中的5种数据存储方式,结合实例形式 ...

  5. Android学习之基础知识九—数据存储(持久化技术)

    数据持久化是将那些内存中的瞬时数据保存到存储设备,保证即使在手机或电脑关机的情况下,这些数据仍然不会丢失. Android系统中主要提供了3种方式用于简单地实现数据持久化功能:文件存储.SharedP ...

  6. Android开发之利用SQLite进行数据存储

    Android开发之利用SQLite进行数据存储 Android开发之利用SQLite进行数据存储 SQLite数据库简单介绍 Android中怎样使用SQLite 1 创建SQLiteOpenHel ...

  7. 四种常见的 POST-------- content-type数据提交方式

    HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS.GET.HEAD.POST.PUT.DELETE.TRACE.CONNECT 这几种.其中 POST 一般用来向服务端提交数据,本文 ...

  8. Android中使用Gson解析JSON数据的两种方法

    Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率;本文将介绍两种方法解析JSON数据,需要的朋友可以参考下   Json是一种类似于XML的通用数据交换格式,具有比XML更高的 ...

  9. Android Volley获取json格式的数据

    为了让Android能够快速地访问网络和解析通用的数据格式Google专门推出了Volley库,用于Android系统的网络传输.volley库可以方便地获取远程服务器的图片.字符串.json对象和j ...

随机推荐

  1. 通过几个例子看sed的模式空间与保持空间

    SED之所以能以行为单位的编辑或修改文本,其原因在于它使用了两个空间:一个是活动的“模式空间(pattern space)”,另一个是起辅助作用的“暂存缓冲区(holdingspace)这2个空间的使 ...

  2. mvc 验证登录

    很多时候,我们需要多个页面验证用户是否登录 有2中方法. 一种是继承 Attrbuite属性,添加验证,这个可以网上搜索. 我一般使用下面的方式 创建BaseWebController继承Contro ...

  3. Sightseeing tour HDU - 1956(混合欧拉回路)

    题意: 有n个点,m条边,其中有单向边和双向边,求是否存在欧拉回路 解析: 刚开始想...判断一下每个点的度数不就好了...emm..还是年轻啊.. 判断是解决不了问题的,因为可能会有某两个点冲突,比 ...

  4. MT【31】傅里叶级数为背景的三角求和

    接下来要讲的这道题,背景有点复杂,不要求99%的学生看的懂背景,但是解答过程中涉及的反证法以及第二数学归纳法对自主招生的学生来说倒是不错的学习机会. 解答: 评 : 本题的背景为高等数学中的傅里叶分析 ...

  5. MT【29】介绍向量的外积及应用举例

    我们在学校教材里学到的数量积(内积)其实还有一个孪生兄弟向量积(外积),这个对参加自主招生以及竞赛的学生来讲是需要掌握的,这里稍作介绍: 原理: 例题: 应用:

  6. Linux 下 wordpress 无法安装插件

    修改目录权限mkdir -p wp-content/tmpchown -R www:www  wp-contentchmod -R 777 wp-content 配置修改wp-config.php搜索 ...

  7. 16 利用Zabbix完成windows监控

    点击返回:自学Zabbix之路 16 利用Zabbix完成windows监控 1.安装zabbix_agentd 1.1.下载zabbix_agentd监控客户端软件安装包(windows操作系统客户 ...

  8. 自学Zabbix3.12.4-动作Action-Operation配置

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 3.12.4 自学Zabbix3.12.4-动作Action-Operation配置 1. 概述 ...

  9. Spring MVC 起步

    跟踪Spring MVC的请求 在请求离开浏览器时①,会带有用户所请求内容的信息,至少会包含请求的URL. 请求旅程的第一站是Spring的DispatcherServlet.与大多数基于Java的W ...

  10. protobuf for java

    本文档为java编程人员使用protocol buffer提供了一个基本的介绍,通过一个简单的例程进行介绍.通过本文,你可以了解到如下信息: 1.在一个.proto文件中定义一个信息格式. 2.使用p ...