HTTP协议中有两种不同的请求方式——GET方式和POST方式。
所以,在进行HTTP编程前,首先要明确究竟使用的哪种方式进行数据请求的。
HttpURLConnection conn = null;
String strUrl = "http://www.baidu.com";
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
在HttpClient中,我们可以非常轻松使用HttpGet对象来通过GET方式进行数据请求操作,当获得HttpGet对象后我们可以使用HttpClient的execute方法来向我们的服务器发送请求。在发送的GET请求被服务器相应后,会返回一个HttpResponse响应对象,利用这个响应的对象我们能够获得响应回来的状态码,如:200、400、401等等。
public String HttpGetMethod() { String result = ""; try { HttpGet httpRequest = new HttpGet(strUrl); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(httpResponse.getEntity()); } else { result = "null"; } return result; } catch (Exception e) { return null; }
}
当我们使用POST方式时,我们可以使用HttpPost类来进行操作。当获取了HttpPost对象后,我们就需要向这个请求体传入键值对,这个键值对我们可以使用NameValuePair对象来进行构造,然后再使用HttpRequest对象最终构造我们的请求体,最后使用HttpClient的execute方法来发送我们的请求,并在得到响应后返回一个HttpResponse对象。其他操作和我们在HttpGet对象中的操作一样。
public String HttpPostMethod(String key, String value) { String result = ""; try { // HttpPost连接对象 HttpPost httpRequest = new HttpPost(strUrl); // 使用NameValuePair来保存要传递的Post参数 List params = new ArrayList(); // 添加要传递的参数 params.add(new BasicNameValuePair(key, value)); // 设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params, "Utf-8"); // 请求httpRequest httpRequest.setEntity(httpentity); // 取得默认的HttpClient HttpClient httpclient = new DefaultHttpClient(); // 取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // HttpStatus.SC_OK表示连接成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 取得返回的字符串 result = EntityUtils.toString(httpResponse.getEntity()); return result; } else { return "null"; } } catch (Exception e) { return null; }
}
android网络框架之OKhttp,一个处理网络请求的开源项目,是安卓端最火热的轻量级框架。android在开发的时候很少直接与数据库打交道,所以就有了通过接口的方式使android与数据库间接通信,通信方式就是使用okhttp插件。
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
OkHttp分为get和post请求,在这两种请求中又分为同步和异步的请求。同步的意思就是得等到服务器有相应才会继续往下走,所以同步的方式都需要开启一个线程。
//注意网络同步请求必须要有一个子线程//get同步请求public void getSync(View view) {new Thread(){@Overridepublic void run() {//get请求参数可以直接写在url后面//https://www.httpbin.org/get为开源测试网址Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();//请求的call对象Call call=okHttpClient.newCall(request);try{Response response =call.execute();Log.e("get同步请求:", "getSync:"+response.body().string() );}catch (IOException e){e.printStackTrace();}}}.start();}
//异步不需要创建线程public void getAsync(View view) {Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();//请求的call对象Call call=okHttpClient.newCall(request);//异步请求call.enqueue(new Callback() {//失败的请求@Overridepublic void onFailure(@NonNull Call call, @NonNull IOException e) {}//结束的回调@Overridepublic void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {//响应码可能是404也可能是200都会走这个方法if(response.isSuccessful()){Log.e("get异步请求:", "getASync:"+response.body().string() );}}});}
//okp默认是get请求,post需要有请求体,即formBodypublic void postSync(View view) {new Thread(){@Overridepublic void run() {FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();Request request = new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();//请求的call对象Call call=okHttpClient.newCall(request);try{Response response =call.execute();Log.e("pot同步请求", "postSync:"+response.body().string() );}catch (IOException e){e.printStackTrace();}}}.start();}
public void postAsync(View view) {FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();Request request = new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();Call call=okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(@NonNull Call call, @NonNull IOException e) {}@Overridepublic void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {if(response.isSuccessful()){Log.e("pot异步请求", "postASync:"+response.body().string() );}}});}
package com.example.newnewnet.school;import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import com.example.newnewnet.R;
import com.example.newnewnet.myapplication;
import com.example.newnewnet.entities.newRoot;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class postschooldata extends AppCompatActivity {private TextView showdata;private OkHttpClient okHttpClient;private Map> cookies = new HashMap<>();private String token;@SuppressLint("MissingInflatedId")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_postdata);showdata = findViewById(R.id.showdata);okHttpClient = new OkHttpClient.Builder().build();token = myapplication.token;}public void postData(View view){JsonObject jsonObject = new JsonObject();jsonObject.addProperty("username","user10");jsonObject.addProperty("password","lisnso");MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");RequestBody body = RequestBody.Companion.create(String.valueOf(jsonObject),mediaType);new Thread(() -> {Request request = new Request.Builder().url("http://192.168.176.22:80/rest/account/login").post(body).build();try {Response execute = okHttpClient.newCall(request).execute();String result = execute.body().string();System.out.println(result);runOnUiThread(new Runnable() {@Overridepublic void run() {showdata.setText(Html.fromHtml(result,Html.FROM_HTML_MODE_COMPACT));Gson gson = new Gson();newRoot response = gson.fromJson(result, new TypeToken() {}.getType());token = response.getData().getToken();myapplication.token = token;System.out.println(token);//Intent intent = new Intent(postschooldata.this, querydriveActivity.class);startActivity(intent);}});Log.d("这个是token", String.valueOf(token));} catch (IOException e) {e.printStackTrace();}}).start();}public void userdata(View view){new Thread(() -> {FormBody add = new FormBody.Builder().add("aa", "bb").build();Request request = new Request.Builder().url("http://192.168.176.20/rest/sysmodel/listDeviceControlTypes").addHeader("Content-Type","application/json").addHeader("authorization",token).post(add).build();try {Response execute = okHttpClient.newCall(request).execute();System.out.println(execute.body().string());} catch (IOException e) {e.printStackTrace();}}).start();}
}
package com.example.newnewnet;import android.app.Application;public class myapplication extends Application{private static myapplication mApp;public static String token;public static myapplication getInstance(){return mApp;}
}
打开网络权限