做网站成都求几个能用的地址2021
news/
2025/9/22 20:12:34/
文章来源:
做网站成都,求几个能用的地址2021,西安网站seo分析,中国城乡建设部官网文章目录一、第1种方式1. 因依赖2. 工具类测试方法3. 服务端接收二、第2种方式三、第3种方式3.1. 引依赖3.2. 工具类测试3.3. 服务端代码一、第1种方式
1. 因依赖 !-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --dependency测试方法3. 服务端接收二、第2种方式三、第3种方式3.1. 引依赖3.2. 工具类测试3.3. 服务端代码一、第1种方式
1. 因依赖 !-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --dependencygroupIdcommons-httpclient/groupIdartifactIdcommons-httpclient/artifactIdversion3.1/version/dependency2. 工具类测试方法
package com.gblfy;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;import java.io.InputStream;
import java.io.InputStreamReader;public class HTTPUtils {/*** 协议类型HTTP* 请求方式POST* 报文格式:json* 编码设置UTF-8* 响应类型jsonStr** param url* param json* return* throws Exception*/public static String postJosnContent(String url, String json) throws Exception {System.out.println(请求接口参数 json);PostMethod method new PostMethod(url);HttpClient httpClient new HttpClient();try {RequestEntity entity new StringRequestEntity(json, application/json, UTF-8);method.setRequestEntity(entity);httpClient.executeMethod(method);System.out.println(请求接口路径url method.getURI().toString());InputStream in method.getResponseBodyAsStream();//下面将stream转换为StringStringBuffer sb new StringBuffer();InputStreamReader isr new InputStreamReader(in, UTF-8);char[] b new char[4096];for (int n; (n isr.read(b)) ! -1; ) {sb.append(new String(b, 0, n));}String returnStr sb.toString();return returnStr;} catch (Exception e) {e.printStackTrace();throw e;} finally {method.releaseConnection();}}public static void main(String[] args) throws Exception {String url http://localhost:8080/httptojson;String json {\name\:\gblfy\};String res postJosnContent(url, json);System.out.println(响应报文: res);}
}
3. 服务端接收
package com.gblfy;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;Controller
public class AController {RequestMapping(value /postToJson, method RequestMethod.POST, produces application/json;charsetUTF-8)ResponseBodypublic String postToJson(RequestBody String json) {System.out.println(json);return json;}
}二、第2种方式
和第一种方式基本一样
public static byte[] post(String url, String content, String charset) throws IOException {URL console new URL(url);HttpURLConnection conn (HttpURLConnection) console.openConnection();conn.setDoOutput(true);// 设置请求头conn.setRequestProperty(Content-Type, application/json;charsetutf-8);conn.connect();DataOutputStream out new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、关闭out.flush();out.close();InputStream is conn.getInputStream();if (is ! null) {ByteArrayOutputStream outStream new ByteArrayOutputStream();byte[] buffer new byte[1024];int len 0;while ((len is.read(buffer)) ! -1) {outStream.write(buffer, 0, len);}is.close();return outStream.toByteArray();}return null;}三、第3种方式
3.1. 引依赖 !-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --dependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpclient/artifactId/dependencydependencygroupIdorg.apache.commons/groupIdartifactIdcommons-lang3/artifactIdversion3.9/version/dependency3.2. 工具类测试
package com.gblfy.util;import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;/*** author Mundo* ClassName: HttpClientUtil* Description: TODO*/public class HttpApiUtil {private static final Logger logger LoggerFactory.getLogger(HttpApiUtil.class);/**** param url 请求路径* param params 参数* return*/public static String doGet(String url, MapString, String params) {// 返回结果String result ;// 创建HttpClient对象HttpClient httpClient HttpClientBuilder.create().build();HttpGet httpGet null;try {// 拼接参数,可以用URIBuilder,也可以直接拼接在传值拼在url后面如下--httpGet new// HttpGet(uri?id123);URIBuilder uriBuilder new URIBuilder(url);if (null ! params !params.isEmpty()) {for (Map.EntryString, String entry : params.entrySet()) {uriBuilder.addParameter(entry.getKey(), entry.getValue());// 或者用// 顺便说一下不同(setParameter会覆盖同名参数的值addParameter则不会)// uriBuilder.setParameter(entry.getKey(), entry.getValue());}}URI uri uriBuilder.build();// 创建get请求httpGet new HttpGet(uri);logger.info(访问路径 uri);HttpResponse response httpClient.execute(httpGet);if (response.getStatusLine().getStatusCode() HttpStatus.SC_OK) {// 返回200请求成功// 结果返回result EntityUtils.toString(response.getEntity());logger.info(请求成功返回数据 result);} else {logger.info(请求失败);}} catch (Exception e) {logger.info(请求失败!);logger.error(ExceptionUtils.getStackTrace(e));} finally {// 释放连接if (null ! httpGet) {httpGet.releaseConnection();}}return result;}/*** param url* param params* return* Title: doPost* Description: post请求* author Mundo*/public static String doPost(String url, MapString, String params) {String result ;// 创建httpclient对象HttpClient httpClient HttpClientBuilder.create().build();HttpPost httpPost new HttpPost(url);try { // 参数键值对if (null ! params !params.isEmpty()) {ListNameValuePair pairs new ArrayListNameValuePair();NameValuePair pair null;for (String key : params.keySet()) {pair new BasicNameValuePair(key, params.get(key));pairs.add(pair);}// 模拟表单UrlEncodedFormEntity entity new UrlEncodedFormEntity(pairs);httpPost.setEntity(entity);}HttpResponse response httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() HttpStatus.SC_OK) {result EntityUtils.toString(response.getEntity(), utf-8);logger.info(返回数据 result);} else {logger.info(请求失败url: url);}} catch (Exception e) {logger.error(请求失败);logger.error(ExceptionUtils.getStackTrace(e));e.printStackTrace();} finally {if (null ! httpPost) {// 释放连接httpPost.releaseConnection();}}return result;}/*** post发送json字符串* param url* param params* return 返回数据* Title: sendJsonStr*/public static String sendJsonStr(String url, String params) {String result ;HttpClient httpClient HttpClientBuilder.create().build();HttpPost httpPost new HttpPost(url);try {httpPost.addHeader(Content-type, application/json; charsetutf-8);httpPost.setHeader(Accept, application/json);if (StringUtils.isNotBlank(params)) {httpPost.setEntity(new StringEntity(params, Charset.forName(UTF-8)));}HttpResponse response httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() HttpStatus.SC_OK) {result EntityUtils.toString(response.getEntity());logger.info(返回数据 result);} else {logger.info(请求失败);}} catch (IOException e) {logger.error(请求异常);logger.error(ExceptionUtils.getStackTrace(e));}return result;}/*** 发送http请求的obj报文内置转json** param url* param obj* return*/public static String postJson(String url, Object obj) {HttpURLConnection conn null;try {// 创建一个URL对象URL mURL new URL(url);// 调用URL的openConnection()方法,获取HttpURLConnection对象conn (HttpURLConnection) mURL.openConnection();conn.setRequestMethod(POST);// 设置请求方法为post/* conn.setReadTimeout(5000);// 设置读取超时为5秒conn.setConnectTimeout(10000);// 设置连接网络超时为10秒*/conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容// 设置文件类型:conn.setRequestProperty(Content-Type, application/json; charsetUTF-8);// 设置接收类型否则返回415错误conn.setRequestProperty(accept, application/json);int len 0;// post请求的参数byte[] buf new byte[10240];//String data JSONObject.toJSONString(obj);// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容OutputStream out conn.getOutputStream();// 获得一个输出流,向服务器写数据out.write(data.getBytes());out.flush();out.close();int responseCode conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法if (responseCode 200) {InputStream is conn.getInputStream();String state getStringFromInputStream(is);return state;} else {System.out.print(访问失败 responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if (conn ! null) {conn.disconnect();// 关闭连接}}return null;}public static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream os new ByteArrayOutputStream();// 模板代码 必须熟练byte[] buffer new byte[1024];int len -1;// 一定要写lenis.read(buffer)// 如果while((is.read(buffer))!-1)则无法将数据写入buffer中while ((len is.read(buffer)) ! -1) {os.write(buffer, 0, len);}is.close();String state os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)os.close();return state;}/*** post方式请求服务器(http协议)** param url 请求地址* param content 参数* param charset 编码* return* throws NoSuchAlgorithmException* throws KeyManagementException* throws IOException*/public static byte[] post(String url, String content, String charset) throws IOException {URL console new URL(url);HttpURLConnection conn (HttpURLConnection) console.openConnection();conn.setDoOutput(true);// 设置请求头conn.setRequestProperty(Content-Type, application/json;charsetutf-8);conn.connect();DataOutputStream out new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、关闭out.flush();out.close();InputStream is conn.getInputStream();if (is ! null) {ByteArrayOutputStream outStream new ByteArrayOutputStream();byte[] buffer new byte[1024];int len 0;while ((len is.read(buffer)) ! -1) {outStream.write(buffer, 0, len);}is.close();return outStream.toByteArray();}return null;}public static void main(String[] args) {//测试1 get发送mapMapString, String map new HashMapString, String();map.put(id, UUID.randomUUID().toString());map.put(name, gblfy);String get doGet(http://localhost:8080/getToMap, map);System.out.println(get请求调用成功返回数据是 get);//测试2 post发送map// String post doPost(http://localhost:8080/httptojson, map);// System.out.println(post调用成功返回数据是 post);//测试3 post发送json字符串// String json sendJsonStr(http://localhost:8080/httptojson, {\name\:\ly\});// System.out.println(json发送成功返回数据是 json);//测试4 post发送obj对象// User user new User();// user.setUsername(POST_JSON);// user.setAge(12);// user.setPasswd(00990099);// String json postJson(http://localhost:8080/httptojson, user);// System.out.println(json发送成功返回数据是 json);}
}
3.3. 服务端代码
package com.gblfy;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;Controller
public class AController {RequestMapping(value /postToJson, method RequestMethod.POST, produces application/json;charsetUTF-8)ResponseBodypublic String postToJson(RequestBody String json) {System.out.println(json);return json;}RequestMapping(value /getToMap, method RequestMethod.GET)public String getToMap(RequestParam(name id) String id,RequestParam(name name) String name) {System.out.println(id);System.out.println(name);StringBuffer buf new StringBuffer();buf.append(id);buf.append(name);return buf.toString();}
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/910234.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!