java代码中http请求与https请求

来源:互联网 发布:软件体系结构设计 pdf 编辑:程序博客网 时间:2024/05/21 11:41

1.Java代码中的http请求的服务端与和客户端

a: GET请求(返回字符串)

**服务端代码:**@RequestMapping(value = "/getDriverOnline", method = RequestMethod.GET)@ResponseBodypublic String getDriverOnline(){    System.out.println("======================hello world");    return "111";}**客户端代码:**    @Testpublic 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)@ResponseBodypublic 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)@ResponseBodypublic 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){
}

原创粉丝点击