【Android】安卓开发之使用Gson和POST请求和服务器通信
2017-02-22 18:14
357 查看
一、先看接口文档
url:http://10.15.120.43:8080/APP/Register(假设是这个地址,实际并不是)
请求方式:Http-Post
Content-Type: application/json
请求参数
{ “username”:”用户名”,“password”:”登录密码”}
返回参数
{“code”:”响应状态码”,“msg”: “响应信息”}
二、添加依赖
1、在Android studio 的project的Android视图下,打开build.gradle(Module:app)文件,添加依语句compile 'com.google.code.gson:gson:2.7'
三、打开网络请求
打开manifests文件夹下的AndroidManifest.xml文件,加上<uses-permission android:name="android.permission.INTERNET"/>
/**
* 注册页面2活动
*/
public class RegisterPart2 extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_register_part2);
//---------------------------给状态栏设置颜色-----------------------------------------------
TextView textViewActionBar = (TextView) findViewById(R.id.actionBarId);
setActionBarColor(textViewActionBar, getResources().getColor(R.color.theRed));
//------------------------------------------------------------------------------------------
final EditText regUserName = (EditText) findViewById(R.id.regist2NameEditId);
final EditText regPassword = (EditText) findViewById(R.id.regist2PasswordEditId);
EditText regConfirm = (EditText) findViewById(R.id.regist2ConfirmEditId);
EditText regEmail = (EditText) findViewById(R.id.regist2EmailEditId);
Button confirmButton = (Button) findViewById(R.id.regist2ConfirmBottonId);
/**
* 完成注册,销毁之前的注册活动,直接跳到登陆界面,且不可返回之前注册活动
*/
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//---------------------------获取输入的用户名和密码---------------------------------
String name = regUserName.getText().toString();
String password = regPassword.getText().toString();
//----------------------------------------------------------------------------------
//---------------------通过POST请求将用户名和密码发送给服务器-----------------------
try {
//新建一个线程,通过Message消息通知Handle对UI进行更改,现在只能在UI线程里对UI组件进行更改。
new Thread(new Runnable() {
@Override
public void run() {
//下面三句话,将会把三个参数包装为{"para1":10,"para2":2,"opt":"div"}字段
CalBean tb = new CalBean("12345678902","123456");
Gson gson = new Gson();
//传入的参数
String datas = gson.toJson(tb);
String url = " http://10.1.19.43:8080/Register"; String data = sendPostRequest(url, datas);
}
}).start();
} catch (Exception e) {
Log.i("ok", "there must be something wrong!");
return;
}
//----------------------------------------------------------------------------------
Intent intent = new Intent(RegisterPart2.this, Login.class);
startActivity(intent);
ActivityCollector.finishAll();
}
});
}
public static String sendPostRequest(String url, String param) {
HttpURLConnection httpURLConnection = null;
OutputStream out = null; //写
InputStream in = null; //读
int responseCode = 0; //远程主机响应的HTTP状态码
String result = "";
try {
URL sendUrl = new URL(url);
httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
//post方式请求
httpURLConnection.setRequestMethod("POST");
//设置头部信息
httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
//一定要设置 Content-Type 要不然服务端接收不到参数
httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
//指示应用程序要将数据写入URL连接,其值默认为false(是否传参)
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); //30秒连接超时
httpURLConnection.setReadTimeout(30000); //30秒读取超时
//传入参数
out = httpURLConnection.getOutputStream();
out.write(param.getBytes());
out.flush(); //清空缓冲区,发送数据
out.close();
responseCode = httpURLConnection.getResponseCode();
//获取请求的资源
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
result = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> map = new Gson().fromJson(result, new TypeToken<Map<String, String>>(){}.getType());
String msg = map.get("msg");
return msg;
}
}
最后设一个断点看一下效果:
url:http://10.15.120.43:8080/APP/Register(假设是这个地址,实际并不是)
请求方式:Http-Post
Content-Type: application/json
请求参数
{ “username”:”用户名”,“password”:”登录密码”}
返回参数
{“code”:”响应状态码”,“msg”: “响应信息”}
二、添加依赖
1、在Android studio 的project的Android视图下,打开build.gradle(Module:app)文件,添加依语句compile 'com.google.code.gson:gson:2.7'
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' compile 'com.google.code.gson:gson:2.7' }2、点击右上角的 Sync now同步文本,然后Android studio 会自动下载Gson2.7,等它下载完就好了。
三、打开网络请求
打开manifests文件夹下的AndroidManifest.xml文件,加上<uses-permission android:name="android.permission.INTERNET"/>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test"> <uses-permission android:name="android.permission.INTERNET"/> <application四、在Java文件夹下新建一个Bean包,包下新建一个CalBean类,CalBean类里的代码如下:
package Bean; public class CalBean { private String username; private String password; public CalBean(String username,String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "CalBean{" + "username=" + username + ", password=" + password +"}"; } }五、在注册页的Activity类进行相应设置
/**
* 注册页面2活动
*/
public class RegisterPart2 extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_register_part2);
//---------------------------给状态栏设置颜色-----------------------------------------------
TextView textViewActionBar = (TextView) findViewById(R.id.actionBarId);
setActionBarColor(textViewActionBar, getResources().getColor(R.color.theRed));
//------------------------------------------------------------------------------------------
final EditText regUserName = (EditText) findViewById(R.id.regist2NameEditId);
final EditText regPassword = (EditText) findViewById(R.id.regist2PasswordEditId);
EditText regConfirm = (EditText) findViewById(R.id.regist2ConfirmEditId);
EditText regEmail = (EditText) findViewById(R.id.regist2EmailEditId);
Button confirmButton = (Button) findViewById(R.id.regist2ConfirmBottonId);
/**
* 完成注册,销毁之前的注册活动,直接跳到登陆界面,且不可返回之前注册活动
*/
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//---------------------------获取输入的用户名和密码---------------------------------
String name = regUserName.getText().toString();
String password = regPassword.getText().toString();
//----------------------------------------------------------------------------------
//---------------------通过POST请求将用户名和密码发送给服务器-----------------------
try {
//新建一个线程,通过Message消息通知Handle对UI进行更改,现在只能在UI线程里对UI组件进行更改。
new Thread(new Runnable() {
@Override
public void run() {
//下面三句话,将会把三个参数包装为{"para1":10,"para2":2,"opt":"div"}字段
CalBean tb = new CalBean("12345678902","123456");
Gson gson = new Gson();
//传入的参数
String datas = gson.toJson(tb);
String url = " http://10.1.19.43:8080/Register"; String data = sendPostRequest(url, datas);
}
}).start();
} catch (Exception e) {
Log.i("ok", "there must be something wrong!");
return;
}
//----------------------------------------------------------------------------------
Intent intent = new Intent(RegisterPart2.this, Login.class);
startActivity(intent);
ActivityCollector.finishAll();
}
});
}
public static String sendPostRequest(String url, String param) {
HttpURLConnection httpURLConnection = null;
OutputStream out = null; //写
InputStream in = null; //读
int responseCode = 0; //远程主机响应的HTTP状态码
String result = "";
try {
URL sendUrl = new URL(url);
httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
//post方式请求
httpURLConnection.setRequestMethod("POST");
//设置头部信息
httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
//一定要设置 Content-Type 要不然服务端接收不到参数
httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
//指示应用程序要将数据写入URL连接,其值默认为false(是否传参)
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(30000); //30秒连接超时
httpURLConnection.setReadTimeout(30000); //30秒读取超时
//传入参数
out = httpURLConnection.getOutputStream();
out.write(param.getBytes());
out.flush(); //清空缓冲区,发送数据
out.close();
responseCode = httpURLConnection.getResponseCode();
//获取请求的资源
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
result = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> map = new Gson().fromJson(result, new TypeToken<Map<String, String>>(){}.getType());
String msg = map.get("msg");
return msg;
}
}
最后设一个断点看一下效果:
相关文章推荐
- Android开发使用POST方式向服务器请求和发送数据
- Android中使用Json和Xml与服务器进行通信,使用代码发送Get和Post请求,http请求辅助类
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpURLConnection进行POST请求,向服务器上传数据
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android开发之使用HttpURLConnection进行POST请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android开发 Retrofit使用json提交请求服务器
- android之使用get和post方式向服务器提交请求
- 安卓开发请求服务器的两种方式GET与POST(另附验证码的倒计时)
- Android开发 httpClient post方法请求tomcat服务器实现注册登陆
- Android开发笔记-使用Volley开源库进行Http网络请求(POST方式)
- android之使用get和post方式向服务器提交请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用httpPost向服务器发送请求的方法
- Android开发 httpClient post方法请求tomcat服务器实现注册登陆
- "Android下使用HttpUrlConntion"进行最简单的get,post请求(包括创建服务器)
- 安卓开发:使用AsyncTask异步向服务器发起request请求
- HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection
- Android开发之使用Get方法向服务器发送请求