Okhttpサーバへのリクエスト(リクエストヘッダ、フォーム、post jsonデータ)の送信
6766 ワード
:https://github.com/Arisono/Gradle-demo
/** * @desc:post json Header+params+json */ @SuppressWarnings("deprecation") public static void sendHeadersAndJSON() { // RequestBody formBody = new FormBody.Builder() .add("jsonData", "{\"data\":\"121\",\"data1\":\"2232\"}") .add("username", "Arison+ ").add("password", "1111111") .build(); String postBody = "{\"type\":\"post json \"}"; String postBody2 = "{\"type2\":\"post json \"}"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders") .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D") .addHeader("content-type", "application/json;charset:utf-8") .addHeader("Home", "china")// header .addHeader("user-agent", "android") // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody)) .post(formBody) // .put(RequestBody.create( MediaType.parse("application/json; charset=utf-8"), postBody))// post json .put(RequestBody.create( MediaType.parse("application/json; charset=utf-8"), postBody2))// post json .build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String json = response.body().string(); System.out.println(json); String post = JSON.parseObject(json).getString("postBody"); System.out.println(" :" + post); System.out.println(" :" + URLDecoder.decode(post)); } } catch (IOException e) { e.printStackTrace(); } } /** * @desc: Header+params */ public static void sendHeadersAndParams() { String china_str = ""; try { china_str = URLEncoder.encode(" ", "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // RequestBody formBody = new FormBody.Builder().add("query", "Hello") .add("username", "Arison").add("password", "1111111").build(); // /* * RequestBody formBody2 = new FormBody.Builder() .add("search", * "Jurassic Park") .build(); */ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders") .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D") .addHeader("content-type", "text/html;charset:utf-8") .addHeader("Home", "china")// header .addHeader("Home1", china_str)// header .addHeader("user-agent", "android") // .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody)) .post(formBody) // .post(formBody2) .build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String json = response.body().string(); System.out.println(json); } } catch (IOException e) { e.printStackTrace(); } } /** * @desc: */ public static void sendHeaders() { String china_str = ""; try { china_str = URLEncoder.encode(" ", "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://localhost:8080/spring-mvc-showcase/api/getHeaders") .header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D") .addHeader("content-type", "text/html;charset:utf-8") .addHeader("Home", "china")// header .addHeader("Home1", china_str)// header .addHeader("user-agent", "android").build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String json = response.body().string(); System.out.println(json); String home1 = JSON.parseObject(json).getJSONObject("headers") .getString("home1"); System.out.println(URLDecoder.decode(home1, "utf-8")); } } catch (IOException e) { e.printStackTrace(); } } /** * @dec * @throws IOException */ public static void sendBasicRequest() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com") .build(); try { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { // throw new IOException(" : " + response); } // Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } // // System.out.println(response.body().string()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Server Coreメソッド:/** * @return */ @RequestMapping(value = "/api/getHeaders") private @ResponseBody LinkedHashMap
receiveHeaders( HttpServletRequest request, @CookieValue(value = "JSESSIONID", required = false) String sessionId,@RequestBody String postBody) { LinkedHashMap result=new LinkedHashMap (); Map header=new HashMap (); Map params=new HashMap (); result.put("postBody", postBody); @SuppressWarnings("rawtypes") Enumeration paramNames =request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = (String) paramNames.nextElement(); Object value = request.getParameter(key); params.put(key, value); } result.put("params", params); @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); header.put(key, value); } result.put("headers", header); result.put("JSESSIONID", sessionId); System.out.println(result.toString()); return result; }
参照ドキュメント:
https://github.com/square/okhttp/wiki/Recipes