Android客户端OkHttp的使用以及tomcat服务器的解析客户端发过来的数据
七月的四字 人气:02020-02-15 21:25:42
### android客户端客户向服务器发送json字符串或者以参数请求的方式发送数据
其中又分为post请求和get请求
1.activity.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:app="http://schemas.android.com/apk/res-auto" 5 xmlns:tools="http://schemas.android.com/tools" 6 android:layout_width="match_parent" 7 android:background="#FFF" 8 android:orientation="vertical" 9 android:layout_height="match_parent"> 10 11 <TextView 12 android:id="@+id/tv_okhttp" 13 android:layout_width="match_parent" 14 android:layout_height="wrap_content" 15 android:text="abcdef"/> 16 <Button 17 android:id="@+id/button_activity7" 18 android:background="@drawable/testt" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" /> 21 <Button 22 android:id="@+id/button_activity7_2" 23 android:background="@drawable/testt" 24 android:layout_width="wrap_content" 25 android:layout_height="wrap_content" /> 26 </LinearLayout>
2.mainactivity.java
package com.lianggao.whut.thirdtest; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONStringer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity7 extends Activity implements View.OnClickListener { private static final String TAG = "MainActivity7"; private Button btn_login; private EditText editText_name; private EditText editText_age; private ProgressBar progressBar; private TextView tv_okhttp; private OkHttpClient client=new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main7); findViewById(R.id.button_activity7).setOnClickListener(this); findViewById(R.id.button_activity7_2).setOnClickListener(this); tv_okhttp=(TextView)findViewById(R.id.tv_okhttp); } //忽略这里,这里是用HttpURLConnection进行Get请求的,传递的是参数 private String getUserInfo(String userid){ String path="http://192.168.1.8:8080/com.lianggao.whut/Get_Resopnce_Servlet?name=lianggao&&age="+userid; try { URL url=new URL(path); HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setRequestMethod("GET"); if(httpURLConnection.getResponseCode()==200){ InputStream is=httpURLConnection.getInputStream(); return dealResponseResult(is); } } catch (Exception e) { e.printStackTrace(); } return null; } private String dealResponseResult(InputStream inputStream){ String resultData=null; ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); byte[] data=new byte[1024]; int len=0; try { while((len = inputStream.read(data))!= -1){ byteArrayOutputStream.write(data,0,len); } } catch (IOException e) { e.printStackTrace(); } resultData=new String(byteArrayOutputStream.toByteArray()); return resultData; } //忽略这里是用HttpUrlConnection来post请求的,传递的是json转换的字符流 private String login(String username,String password){ String path="http://192.168.1.8:8080/com.lianggao.whut/Get_Resopnce_Servlet"; try { URL url=new URL(path); HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setRequestMethod("POST"); String data="{'name':'lianggao','age':12}"; httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Content-Type","text/json;charset=utf-8"); OutputStream outputStream=httpURLConnection.getOutputStream(); outputStream.write(data.getBytes()); if(httpURLConnection.getResponseCode()==200){ InputStream is=httpURLConnection.getInputStream(); return dealResponseResult(is); } } catch (Exception e) { e.printStackTrace(); } return null; }
@Override public void onClick(View v) { new TestGetOrPostThread(v).start(); } public class TestGetOrPostThread extends Thread{ private View view ; public TestGetOrPostThread(View view){ this.view=view; } @Override public void run() { switch (view.getId()){ case R.id.button_activity7: /*String getResult=getUserInfo("12"); Log.i("MainActivity","get获取用户信息"+getResult);*/ //getUserInfo(); break; case R.id.button_activity7_2: /* String getResult2=login("lianggao","12"); Log.i("MainActivity","post登录结果"+getResult2);*/ login2(); break; } } } //get请求,参数已经写好name,age,在服务器端可以直接得到请求参数来获得 private void getUserInfo(){ Request.Builder builder=new Request.Builder().url("http://192.168.1.8:8080/com.lianggao.whut/Get_Resopnce_Servlet?name=lianggao&&age=12"); execute(builder); } private void execute(Request.Builder builder){ Call call=client.newCall(builder.build()); call.enqueue(callcack); } private Callback callcack=new Callback(){ @Override public void onFailure(Call call, IOException e) { Log.i("MainActivity","onFailure"); e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String str=new String(response.body().bytes(),"utf-8"); Log.i("MainActivity","onResponse"+str); android.os.Message message= Handlerokhttp.obtainMessage(); message.obj=str; message.sendToTarget(); } }; private Handler Handlerokhttp=new Handler(){ @Override public void handleMessage(Message msg) { String result=(String)msg.obj; Gson gson=new Gson(); User user=gson.fromJson(result,User.class); tv_okhttp.setText(user.getName()+user.getAge()); } }; //post请求传递参数 private void login(){ FormBody.Builder formBuilder=new FormBody.Builder(); formBuilder.add("name","lianggao"); formBuilder.add("age","12"); RequestBody requestBody=formBuilder.build(); Request.Builder builder=new Request.Builder().url("http://192.168.1.8:8080/com.lianggao.whut/Get_Resopnce_Servlet").post(requestBody); execute(builder); } //post请求传递json转换的流,在服务器端需要用GSON解析出来, private void login2(){ String str="{'name':'lianggao','age':12}"; MediaType JSON=MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody2=RequestBody.create(JSON,str); Request.Builder request=new Request.Builder().url("http://192.168.1.8:8080/com.lianggao.whut/Get_Resopnce_Servlet").post(requestBody2); execute(request); } }
3.服务器端
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收参数 /* try { if(request.getParameter("name").trim()!=null&&request.getParameter("age")!=null) { String name=request.getParameter("name").trim(); int age=Integer.parseInt(request.getParameter("age")); String jsonStr=""; Gson gson=new Gson(); if(name.equals("lianggao")&&age==12) { User2 user=new User2(); user.setAge(age); user.setName(name); user.setResult("true"); jsonStr=gson.toJson(user); } else { User2 user=new User2(); user.setAge(age); user.setName(name); user.setResult("false"); jsonStr=gson.toJson(user); } response.getWriter().append(jsonStr); return; } } catch (Exception e) { // TODO: handle exception } */ //接收json流 response.setContentType("application/json;charset=utf-8");//这里可能修改为text/json String message; User user ; try { BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8")); StringBuffer sb=new StringBuffer(""); String temp; while((temp=br.readLine())!=null) { sb.append(temp); } br.close(); message=sb.toString(); System.out.println("请求报文"+message); Gson gson=new Gson(); user=gson.fromJson(message, User.class); if((user.getName().equals("lianggao"))&&(user.getAge()==12)){ User2 user2=new User2(); user2.setAge(user.getAge()); user2.setName(user.getName()); user2.setResult("true"); String jsonStr=gson.toJson(user2); response.getWriter().append(jsonStr); return; }else { User2 user2=new User2(); user2.setAge(user.getAge()); user2.setName(user.getName()); user2.setResult("false"); String jsonStr=gson.toJson(user2); response.getWriter().append(jsonStr); return; } } catch (Exception e) { // TODO: handle exception } } }
加载全部内容