目录
code:
https://download.csdn.net/download/weixin_42749765/11470677
获取
request 获取 params 数据
@RequestMapping(value = "/getTest", produces = { "application/xhtml+xml;charset=UTF-8" })
public String getTest(HttpServletRequest req) {
String params = req.getParameter("params") == null ? "" : req.getParameter("params");
System.out.println(params);
return params;
}
request 获取 raw数据
@RequestMapping(value = "/getTest1", produces = { "application/xhtml+xml;charset=UTF-8" })
public String getTest1(HttpServletRequest req) {
String params = readRaw(req);
System.out.println(params);
return params;
}
//java获取raw
public static String readRaw(HttpServletRequest request) {
String result = "";
try {
InputStream inputStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
result = new String(outSteam.toByteArray(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
依赖
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
请求
发送post params 调用
//keyval params 方式表单
Map<String, Object> mp = new HashMap<String, Object>();
mp.put("params", 123);
String sr1 = HttpRequestUitlTest.sendPostParams("http://localhost:9996/getTest1", mp);
System.out.println(sr1);
发送post params
/**
* post请求(用于key-value格式的参数) 主调用
*
* @param url
* @param params
*
* @return
*/
public static String sendPostParams(String url, Map params) {
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
// 设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
// System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if (code == 200) { // 请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
} else { //
System.out.println("状态码:" + code);
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
发送post raw 调用
JSONObject jsonObject = new JSONObject();
jsonObject.put("params", "{'chaincodeID':{'name':'fscs'},'ctorMsg': {'args':['query','Bob']}}");
jsonObject.put("id", 5);
String transJson = jsonObject.toString();
// 发送 POST httclient 请求 raw
String sr2 = HttpRequestUitlTest.sendPostRaw("http://localhost:9996/getTest1", transJson);
System.out.println(sr2);
发送post raw
/**
*
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param
*
* @return 所代表远程资源的响应结果
*
*/
public static String sendPostRaw(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
依赖
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
pom依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
ok
持续更新