1. 程式人生 > >java程式碼中http請求與https請求

java程式碼中http請求與https請求

可以參照試用RestTemplate與OKHttp3實現該功能

1.Java程式碼中的http請求的服務端與和客戶端

a: GET請求(返回字串)

**服務端程式碼:**
@RequestMapping(value = "/getDriverOnline", method = RequestMethod.GET)
@ResponseBody
public String getDriverOnline(){
    System.out.println("======================hello world");
    return "111";
}
**客戶端程式碼:**
    @Test
public void run2(){
    //1.設定url路徑
    String url = "";
    String param = "";
    HttpResponse response = null;
    try {
        HttpClient httpClient = HttpClients.createDefault();  //獲得客戶端物件
        HttpGet httpGet = new HttpGet(url + "?" + param);
        response = httpClient.execute(httpGet);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }catch (Exception e){
    }
}

輸出的結果是111

b : GET請求(返回物件)

客戶端程式碼:

public void run2(){
    //1.設定url路徑
    String url = "";
    String param = "id=" + 1;
    HttpResponse response = null;
    try {
        HttpClient httpClient = HttpClients.createDefault();  //獲得客戶端物件
        HttpGet httpGet = new HttpGet(url + "?" +param);
        response = httpClient.execute(httpGet);
        String responseJsonString = EntityUtils.toString(response.getEntity()); //獲得返回體轉換成字串
        JSONObject json1 = JSON.parseObject(responseJsonString);;//轉換成json格式,此處是阿里巴巴json
        String studentChina=  json1.get("studentChina");//獲取相應欄位的值
        System.out.println("studentChina =" + studentChina);
    }catch (Exception e){
        System.out.println("異常");
    }
}

服務端程式碼:

  @RequestMapping(value = "/getDriverOnline", method = RequestMethod.GET)
@ResponseBody
public Student getDriverOnline(@RequestParam("id") String id){
    System.out.println("======================hello world");
    Student student = new Student();
    student.setAge("age");
    student.setStudentChina(id);
    student.setStudentName("studentName");
    return student;
}

POST請求:

客戶端程式碼:

package com.xman.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class test {
private static Logger logger = LoggerFactory.getLogger(test.class);
@Test
public void run2(){
//1.設定url路徑
String url = “”;
HttpResponse response = null;
try {
HttpClient httpClient = HttpClients.createDefault(); //獲得客戶端物件
HttpPost httpPost = new HttpPost(url);
JSONObject json = new JSONObject();
json.put(“studentName”,”張三”);
json.put(“age”,”15”);
json.put(“studentChina”,”中國”);
List list = new ArrayList();
list.add(new BasicNameValuePair(“student”, URLEncoder.encode(json.toJSONString())));
//上面的student欄位對應的是服務端的接受的引數@RequestParam(“student”)
httpPost.setEntity(new UrlEncodedFormEntity(list));
response = httpClient.execute(httpPost);
String responseJsonString = EntityUtils.toString(response.getEntity());
System.out.println(“response:” + responseJsonString);
JSONObject json1 = JSON.parseObject(responseJsonString);
System.out.println(“json1:” + json1);
System.out.println(“studentChina :” + json1.getString(“studentChina”));
}catch (Exception e){
System.out.println(“異常”);
}
}
}

服務端程式碼:

 @RequestMapping(value = "/getDriverOnline", method =        RequestMethod.POST)
@ResponseBody
public Student getDriverOnline(@RequestParam("student") String  s){
    System.out.println("======================hello world");
    String  jsonString = URLDecoder.decode(s);
    logger.info("接收到的引數是:"+jsonString);
    System.out.println(jsonString);
    Student student  = JSON.parseObject(jsonString, Student.class);
    student.setAge(student.getAge());
    student.setStudentChina(student.getStudentChina());
    student.setStudentName(student.getStudentName());
    return student;
}

HTTPS請求程式碼:

https請求會涉及到加密的一些協議。需要把HttpClient物件換一下即可。
在http請求的時候,我們建立HttpClient物件使用的方法是:
HttpClient httpClient = HttpClients.createDefault();
現在使用Https請求我們建立物件的方式是:
HttpClient httpClient = new SSLClient();
其中附上SSLClient的程式碼:

package com.xman.test.util;

import org.apache.http.conn.ClientConnectionManager; import
org.apache.http.conn.scheme.Scheme; import
org.apache.http.conn.scheme.SchemeRegistry; import
org.apache.http.conn.ssl.SSLSocketFactory; import
org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import
java.security.cert.CertificateException; import
java.security.cert.X509Certificate;

/* Created by xu on 2017/9/22. */ public class SSLClient extends
DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance(“TLS”);
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme(“https”, 443, ssf));
} }

注:判斷是否返回成功,可以使用 if (response.getStatusLine().getStatusCode() != 200){
}