请求数据
来源:互联网 发布:小丽和小云在计算 编辑:程序博客网 时间:2024/05/31 19:07
login
public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private Button deng; private Button zhu; private EditText shou; private EditText mi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); deng = (Button) findViewById(R.id.log_but_deng); zhu = (Button) findViewById(R.id.log_but_zhu); shou = (EditText) findViewById(R.id.log_shou); mi = (EditText) findViewById(R.id.log_mi); deng.setOnClickListener(this); zhu.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.log_but_deng: String name = shou.getText().toString().trim(); String pwd = mi.getText().toString().trim(); HttpUtil.getInstance(this).doGet("http://120.27.23.105/user/login?mobile=" + name + "&password=" + pwd, LoginBean.class, new OnNetListener() { @Override public void onSuccess(BaseBean baseBean) throws IOException { Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show(); Intent intent=new Intent(LoginActivity.this,MainActivity.class); startActivity(intent); finish(); } @Override public void onError(IOException e) { } }); break; case R.id.log_but_zhu: Intent intent=new Intent(LoginActivity.this,ReginActivity.class); startActivity(intent); finish(); break; } } private boolean is() { String s = shou.getText().toString(); String ss = mi.getText().toString(); if(TextUtils.isEmpty(s)&&TextUtils.isEmpty(ss)){ Toast.makeText(LoginActivity.this,"不能为空",Toast.LENGTH_SHORT).show(); return false; } return true; }}
lo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.wangziying20171014.LoginActivity" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/log_shou" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="输入手机号" /> <EditText android:id="@+id/log_mi" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/log_shou" android:layout_marginTop="16dp" android:hint="输入密码" android:password="true" /> <Button android:id="@+id/log_but_deng" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/log_mi" android:layout_marginTop="20dp" android:layout_marginLeft="60dp" android:text="登录" /> <Button android:id="@+id/log_but_zhu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/log_mi" android:layout_alignParentRight="true" android:layout_marginTop="20dp" android:layout_marginRight="60dp" android:text="注册" /> </RelativeLayout></LinearLayout>BaseBeanpackage com.example.bean;/** * Created by peng on 2017/9/27. */public class BaseBean { public String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; }}LoginBean复制解析JsonHttpUtilpackage com.example.net;import android.content.Context;import android.os.Environment;import android.os.Handler;import android.os.Looper;import com.example.bean.BaseBean;import com.google.gson.Gson;import java.io.File;import java.io.IOException;import java.util.Map;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/** * Created by peng on 2017/9/27. */public class HttpUtil { private static volatile HttpUtil httpUtil; private final OkHttpClient client; private Context context; private Handler handler = new Handler(Looper.getMainLooper()); private HttpUtil(Context context) { //缓存目录 File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024; client = new OkHttpClient.Builder()// .addNetworkInterceptor(new CacheInterceptor())// .writeTimeout(20, TimeUnit.SECONDS)// .readTimeout(20, TimeUnit.SECONDS)// .cache(new Cache(sdcache,cacheSize)) .build(); this.context = context; } public static HttpUtil getInstance(Context context) { if (httpUtil == null) { synchronized (HttpUtil.class) { if (httpUtil == null) { httpUtil = new HttpUtil(context); } } } return httpUtil; } public void doPost(String url, Map<String, String> params, final Class clazz, final OnNetListener onNetListener) { //网络判断// if (!NetWorkUtil.isNetworkAvailable(context)) {// Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();// return;// } if (params != null && params.size() > 0) { FormBody.Builder builder = new FormBody.Builder(); params.put("client", "android"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final BaseBean baseBean = (BaseBean) new Gson().fromJson(response.body().string(), clazz);// int code = baseBean.getCode();// if (code == 200) {// handler.post(new Runnable() {// @Override// public void run() {// try {// onNetListener.onSuccess(baseBean);// } catch (IOException e) {// e.printStackTrace();// }// }// });//// } else if (code == 400) {//// } else if (code == 300) {//// } } }); } } public void download(String url, Callback callback) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(callback); } public void doGet(String url, final Class clazz, final OnNetListener onNetListener) { //网络判断// if (!NetWorkUtil.isNetworkAvailable(context)) {// Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();// return;// } Request.Builder builder = new Request.Builder(); builder.url(url); final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); String code = baseBean.getCode(); handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } }); } /** * @param url * @param params * @param header * @param clazz * @param onNetListener */ /* public void doGet(String url, HashMap<String, String> params, HashMap<String, String> header, final Class clazz, final OnNetListener onNetListener) { //网络判断// if (!NetWorkUtil.isNetworkAvailable(context)) {// Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();// return;// } Request.Builder builder = new Request.Builder(); if (params != null && params.size() > 0) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(url); sb.append("?"); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } url = sb.toString(); } builder.url(url); //添加请求头 if (params != null && header.size() > 0) { for (Map.Entry<String, String> entry : params.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); *//*int code = baseBean.getCode(); if (code == 200) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { }*//* } }); }*/ /** * 上传 * * @param url * @param fileName */ public void uploadFile(String url, String fileName) { String file = Environment.getExternalStorageState() + "/" + fileName; RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", fileName, fileBody).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 下载 * * @param url */ public void download(String url) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }}OnNetListenerpackage com.example.net;import com.example.bean.BaseBean;import java.io.IOException;/** * Created by peng on 2017/9/27. */public interface OnNetListener { public void onSuccess(BaseBean baseBean) throws IOException; public void onError(IOException e);}Reginpackage com.example.wangziying20171014;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import com.example.bean.BaseBean;import com.example.bean.ReBean;import com.example.net.HttpUtil;import com.example.net.OnNetListener;import java.io.IOException;public class ReginActivity extends AppCompatActivity implements View.OnClickListener { private EditText regin_shou; private EditText regin_mi; private Button wan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_regin); regin_shou = (EditText)findViewById(R.id.regin_shou); regin_mi = (EditText)findViewById(R.id.regin_mi); wan = (Button)findViewById(R.id.regin_but_wan); wan.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.regin_but_wan: String name = regin_shou.getText().toString().trim(); String pwd = regin_mi.getText().toString().trim(); HttpUtil.getInstance(this).doGet("http://120.27.23.105/user/reg?mobile=" + name + "&&password=" + pwd, ReBean.class, new OnNetListener() { @Override public void onSuccess(BaseBean baseBean) throws IOException { Toast.makeText(ReginActivity.this,"注册成功",Toast.LENGTH_SHORT).show(); Intent intent=new Intent(ReginActivity.this,LoginActivity.class); startActivity(intent); finish(); } @Override public void onError(IOException e) { } }); break; } }}reg.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.wangziying20171014.ReginActivity" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/regin_shou" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="输入手机号" /> <EditText android:id="@+id/regin_mi" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/regin_shou" android:layout_marginTop="16dp" android:hint="输入密码" android:password="true" /> <Button android:id="@+id/regin_but_wan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/regin_mi" android:layout_marginTop="20dp" android:layout_marginLeft="200dp" android:text="完成" /> </RelativeLayout></LinearLayout>依赖compile 'com.squareup.okhttp3:okhttp:3.9.0'
main网格
package com.example.wangziying.recylerviewdome;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.View;import android.widget.Button;import com.example.wangziying.Itembean.Itembean;import com.example.wangziying.Myadapter.MyAdapter;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RecyclerView rv; private List<Itembean> list=new ArrayList<>(); private Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rv = (RecyclerView) findViewById(R.id.main_rv); but = (Button) findViewById(R.id.main_but); but.setOnClickListener(this); show(true); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.main_but: String s = but.getText().toString(); if("网格".equals(s)){ show(false); but.setText("垂直"); }else{ show(true); but.setText("网格"); } break; } } private void show(boolean flag){ rv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); RecyclerView.LayoutManager layoutManager=null; if(flag){ layoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); }else{ layoutManager=new GridLayoutManager(this,2); } rv.setLayoutManager(layoutManager); // rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL)); for(int i=0;i<100;i++){ Itembean itembean = new Itembean("name" + i, "age" + i); list.add(itembean); } MyAdapter adapter=new MyAdapter(this,list); rv.setAdapter(adapter); }}Adapterpackage com.example.wangziying.Myadapter;import android.content.Context;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import com.example.wangziying.Itembean.Itembean;import com.example.wangziying.recylerviewdome.R;import java.util.ArrayList;import java.util.List;/** * Created by wangziying on 2017/10/12. */public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private List<Itembean> list=new ArrayList<>(); public MyAdapter(Context context, List<Itembean> list) { this.context = context; this.list = list; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false); Type1Viewholder type1Viewholder = new Type1Viewholder(view); return type1Viewholder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Itembean itembean = list.get(position); Type1Viewholder type1Viewholder=(Type1Viewholder) holder; type1Viewholder.item_tv_name.setText(itembean.getName()); type1Viewholder.item_tv_age.setText(itembean.getAge()); } @Override public int getItemCount() { return list.size(); } private class Type1Viewholder extends RecyclerView.ViewHolder{ private TextView item_tv_name; private TextView item_tv_age; public Type1Viewholder(View itemView) { super(itemView); item_tv_name = itemView.findViewById(R.id.item_tv_name); item_tv_age = itemView.findViewById(R.id.item_tv_age); } }}main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.wangziying.recylerviewdome.MainActivity" android:orientation="vertical"> <Button android:id="@+id/main_but" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="网格"/><android.support.v7.widget.RecyclerView android:id="@+id/main_rv" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView></LinearLayout>iteambeanpublic class Itembean { private String name; private String age; public Itembean(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Itembean{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; }}item.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="200dp" android:layout_height="100dp" android:orientation="horizontal"> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:layout_marginTop="5dp" android:src="@mipmap/ic_launcher"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/item_tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="25dp" android:layout_marginTop="10dp" android:text="名字" android:textSize="25dp" /> <TextView android:id="@+id/item_tv_age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="25dp" android:layout_marginTop="5dp" android:text="年龄" android:textSize="25dp" /> </LinearLayout></LinearLayout>
阅读全文
0 0
- 数据请求
- 请求数据
- 数据请求
- 请求数据
- 请求数据
- 请求数据
- HttpPost请求方式请求数据
- XML 数据请求与JSON 数据请求
- 网络数据请求
- ActionInvocation,(请求)数据对象
- qml 请求网络数据
- Request获取请求数据
- 异步请求数据__flash
- JQuery请求JSON数据
- NSURLConnection请求网页数据
- ASIHTTPRequest异步请求数据
- ASIHTTPRequest 保存请求数据
- ASIHTTPRequest请求网页数据
- LeetCode485:Max Consecutive Ones 解答
- 【makefile】一起写makefile(四)--makefile书写命令
- Hibernate 注解开发
- 拦截器的运用
- angular
- 请求数据
- 关于Debug版删除后,release版安装失败的解决方案(仅供自己查阅)
- android+简单的登录界面+OKhttp请求
- angular简单替换
- HTML随机数掷筛子比较
- 商品表
- 【makefile】一起写makefile(五)--变量的使用
- 第二周
- MainActivity