【java程序員理解HTTP】【6】實踐--java 中幾種模擬 http 請求的方式

幾種方式或說方案

Jdk自己提供 java.net 包的 HttpURLConnectionjava

Apache提供HttpClientweb

Spring Web提供RestTemplatespring

以上均可以在java代碼中模擬實現http請求,是隨着技術的進步出來的,整體上愈來愈方便了,之後也可能會出現更高級、更方便的發起http請求的工具類。apache

Jdk自己提供 java.net 包的 HttpURLConnection

由於是jdk自帶的,因此maven中不須要引入任何東西能夠直接使用。json

Apache提供HttpClient

Maven中須要引入apache相關包服務器

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.3.5</version>

</dependency>

Spring Web提供RestTemplate

org.springframework.web.client.RestTemplateapp

項目中只須要加入spring-web的依賴就能夠了。maven

★本身實踐

背景及要求:get方式實現登陸獲取用戶信息

啓動本機的某項目。訪問登陸連接,從其返回信息中獲取用戶真實姓名realName信息。連接以下:工具

http://localhost:1008/LoginService/login?userName=admin&password=123ui

返回結果信息

{

  "resultCode" : 0,

  "result" : {

    "userId" : 1,

    "userName" : "admin",

    "realName" : "admin",

    "password" : "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",

    "isEnabled" : "1",

    "mobilePhone" : null,

    "createUser" : "sys",

    "createDate" : "1970-01-01 00:00:00.0",

    "updateUser" : "sys",

    "updateDate" : "1970-01-01 00:00:00.0",

    "expireDate" : "2050-01-01 00:00:00.0"

  },

  "msgId" : "6388f2f2-1fa8-42dc-b7dc-f650a5589ae1",

  "errorMsg" : null

}

HttpURLConnection實現get請求

package com.ding.thirdService.httpURLConnection;


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

import java.util.Map;


import org.json.JSONException;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;


import com.alibaba.fastjson.JSON;


/**

 *

 * Description:使用 java.net 包的 HttpURLConnection 模擬 http 請求

 *

 */

@RestController

@RequestMapping(value = "/javanet")

public class HttpURLConnectionController {


    @RequestMapping(value = "/call")

    public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password) throws JSONException, IOException {

    

     URL url = new URL("http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password);//若是有參數,在網址中攜帶參數

        URLConnection conn = url.openConnection();

        InputStream is = conn.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader br = new BufferedReader(isr);

        

        String line;

        StringBuilder builder = new StringBuilder();

        while((line=br.readLine())!=null){

              builder.append(line);

        }

        br.close();

        isr.close();

        is.close();

        

        String data = builder.toString();

        

        System.out.println(data);

        

        if(data == null || data.length() == 0){

         return "未獲取數據";

        }



/**

 * 數據的接收的處理

 */


//判斷請求是否成功JSONObject

        Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);

String resultCode = String.valueOf(maps.get("resultCode"));

//失敗了

if(!(null != resultCode && resultCode.contains("0"))){

return "獲取失敗";

}


/**

 * 成功的話則返回自定義的數據格式

 */

String detail = String.valueOf(maps.get("result"));

Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);

return JSON.toJSONString(d.get("realName"));


    }

}

HttpClient方式實現get請求

package com.ding.thirdService.httpClient;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Map;


import org.json.JSONException;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;


import com.alibaba.fastjson.JSON;


/**

 *

 * Description:使用 Apache 包的 HttpClient 模擬 http 請求

 *

 */

@RestController

@RequestMapping(value = "/client")

public class HttpClientController {


@RequestMapping(value = "/call")

public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password)

throws JSONException, IOException {


// 若是有參數,在網址中攜帶參數

URL url = new URL("http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.addRequestProperty("encoding", "UTF-8");

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod("POST");


OutputStream os = conn.getOutputStream();

OutputStreamWriter osw = new OutputStreamWriter(os);

BufferedWriter bw = new BufferedWriter(osw);


bw.write("向服務器傳遞的參數");

bw.flush();


InputStream is = conn.getInputStream();

InputStreamReader isr = new InputStreamReader(is);

BufferedReader br = new BufferedReader(isr);

String line;

StringBuilder builder = new StringBuilder();

while ((line = br.readLine()) != null) {

builder.append(line);

}


String data = builder.toString();

// 關閉資源

System.out.println(data);


if(data == null || data.length() == 0){

return "未獲取數據";

}


/**

 * 數據的接收的處理

 */


// 判斷請求是否成功JSONObject

Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);

String resultCode = String.valueOf(maps.get("resultCode"));

//失敗了

if(!(null != resultCode && resultCode.contains("0"))){

return "獲取失敗";

}


/**

 * 成功的話則返回自定義的數據格式

 */

String detail = String.valueOf(maps.get("result"));

Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);

return JSON.toJSONString(d.get("realName"));


}

}

RestTemplate方式實現get請求

package com.ding.thirdService.restTemplate;


import java.util.Map;


import org.json.JSONException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;


import com.alibaba.fastjson.JSON;


/**

 *

 * Description:RestTemplate 使用

 *

 */

@RestController

@RequestMapping(value = "/restTemplate")

public class RestTemplateController {


@Autowired

private RestTemplate restTemplate;


/**

 *

 * Description:RestTemplate 使用

 * @param userName

 * @param password

 * @return

 * @throws JSONException

 */

    @RequestMapping(value = "/call")

    public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password) throws JSONException {

    

     String u = "http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password;


/**

 * String格式接收數據

 */

String data = null;

try{

data = restTemplate.getForObject(u,String.class);

}catch(Exception e){

return e.toString();

}


System.out.println(data);



/**

 * 數據的接收的處理

 */


//判斷請求是否成功JSONObject

Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);

String resultCode = String.valueOf(maps.get("resultCode"));

//失敗了

if(!(null != resultCode && resultCode.contains("0"))){

return "獲取失敗";

}


/**

 * 成功的話則返回自定義的數據格式

 */

String detail = String.valueOf(maps.get("result"));

Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);

return JSON.toJSONString(d.get("realName"));


    }

    

    @RequestMapping(value = "/call2")

    public Integer call2(@RequestParam(value = "jsonString") String jsonString) throws JSONException {

     return 2;

    }

}

RestTemplate配置類

package com.ding.thirdService.restTemplate.config;


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.client.ClientHttpRequestFactory;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import org.springframework.web.client.RestTemplate;


@Configuration

public class RestTemplateConfig{

    @Bean

    public RestTemplate restTemplate(ClientHttpRequestFactory factory){

        return new RestTemplate(factory);

    }

    

    @Bean

    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

        factory.setReadTimeout(5000);//ms

        factory.setConnectTimeout(15000);//ms

        return factory;

    }

}

三者請求結果同樣

相關文章
相關標籤/搜索