java 怎样发送 POST
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 怎样发送 POST相关的知识,希望对你有一定的参考价值。
向一个网址发送 POST,例如 a=111&b=222&c=333 这样,要求可以设置来源页面、浏览器标示、cookies 等,并且获得 PSOT 之后的网页代码,应该使用哪几个类和引入哪几个包,请详细说明。
private void postMethod(String url) throws IOExceptionurl = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = new NameValuePair("id", "herrapfel"),new NameValuePair("passwd", "") ;
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
System.out.println(" status code:" + statusCode);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
if(statusCode == HttpStatus.SC_OK)
StringBuffer contentBuffer = new StringBuffer();
InputStream in = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,postMethod.getResponseCharSet()));
String inputLine = null;
while((inputLine = reader.readLine()) != null)
contentBuffer.append(inputLine);
System.out.println("input line:"+ inputLine);
contentBuffer.append("/n");
in.close();
else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null)
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
else
System.err.println("Location field value is null.");
参考技术A private void postMethod(String url) throws IOException
url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = new NameValuePair("id", "herrapfel"),new NameValuePair("passwd", "") ;
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
System.out.println(" status code:" + statusCode);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
if(statusCode == HttpStatus.SC_OK)
StringBuffer contentBuffer = new StringBuffer();
InputStream in = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,postMethod.getResponseCharSet()));
String inputLine = null;
while((inputLine = reader.readLine()) != null)
contentBuffer.append(inputLine);
System.out.println("input line:"+ inputLine);
contentBuffer.append("/n");
in.close();
else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null)
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
else
System.err.println("Location field value is null.");
参考技术B
可以使用 Apache HttpComponents 中的 httpcore 和 httpclient 来实现。
http://hc.apache.org/httpcomponents-client-4.3.x/index.html
参考技术C /***HttpUtil.java
*下午02:26:36
*/
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author yoUng
* @description 发送http请求
* @filename HttpUtil.java
* @time 2011-6-15 下午05:26:36
* @version 1.0
*/
public class HttpUtil
public static String http(String url, Map<String, String> params)
URL u = null;
HttpURLConnection con = null;
//构建请求参数
StringBuffer sb = new StringBuffer();
if(params!=null)
for (Entry<String, String> e : params.entrySet())
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append("&");
sb.substring(0, sb.length() - 1);
System.out.println("send_url:"+url);
System.out.println("send_data:"+sb.toString());
//尝试发送请求
try
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
catch (Exception e)
e.printStackTrace();
finally
if (con != null)
con.disconnect();
//读取返回内容
StringBuffer buffer = new StringBuffer();
try
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null)
buffer.append(temp);
buffer.append("\\n");
catch (Exception e)
e.printStackTrace();
return buffer.toString();
参考技术D 楼主难道没听说过 这个开源库吗? HttpClient API ~~~~
java实现发送post请求
1 背景介绍
最近有一个任务,完成数据获取和解析,需要发送带请求参数的post请求,才能拿到数据。之前没有接触过java发送post请求,但有接触过python的requets库,故写下这篇记录一下发送post请求。
2 基本实现
2.1需要的依赖:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
idea会自动识别上面这些类,选择自动导入就好。
2.2 工具类实现
HttpUtils,实现发送:
public class HttpUtils {
public static String sendPostWithJson(String url, String jsonStr, HashMap<String,String> headers) {
// 返回的结果
String jsonResult = "";
try {
HttpClient client = new HttpClient();
// 连接超时
client.getHttpConnectionManager().getParams().setConnectionTimeout(3*1000);
// 读取数据超时
client.getHttpConnectionManager().getParams().setSoTimeout(3*60*1000);
client.getParams().setContentCharset("UTF-8");
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("content-type", headers.get("content-type"));
// 非空
if (null != jsonStr && !"".equals(jsonStr)) {
StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, headers.get("content-type"), "UTF-8");
postMethod.setRequestEntity(requestEntity);
}
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
jsonResult = postMethod.getResponseBodyAsString();
} else {
throw new RuntimeException("接口连接失败!");
}
} catch (Exception e) {
throw new RuntimeException("接口连接失败!");
}
return jsonResult;
}
}
测试:
public static void main(String[] args) {
HashMap<String, String> headers = new HashMap<>(3);
String requestUrl = "http://localhost:8070/test/rz/server/rzxx/at_VaildToken.do";
String jsonStr = "{\\"name\\":\\"张三\\"}";
headers.put("content-type", "application/json");
// 发送post请求
String resultData = HttpUtils.sendPostWithJson(requestUrl, jsonStr,headers);
// 并接收返回结果
System.out.println(resultData);
}
解析使用阿里巴巴的fastJSON,把获取到的字符串变为JSON对象,然后进行遍历取出,最后进行操作,提前数据。
以上是关于java 怎样发送 POST的主要内容,如果未能解决你的问题,请参考以下文章