导航:首页 > 编程语言 > javapost流

javapost流

发布时间:2022-04-14 21:49:01

① 如何使用java模拟post请求

两种选择:一、使用httpclient,二使用java自带的类库。
1、java自带类库:

public static String call(String address,String params) {

URL url = null;

HttpURLConnection httpurlconnection = null;

StringBuilder result = new StringBuilder();

try {

url = new URL(address);

// 以post方式请求

httpurlconnection = (HttpURLConnection) url.openConnection();

httpurlconnection.setDoOutput(true);

httpurlconnection.setRequestMethod("POST");

if(null!=params&¶ms.length()>0){

httpurlconnection.getOutputStream().write(params.getBytes());

httpurlconnection.getOutputStream().flush();

httpurlconnection.getOutputStream().close();

}

// 获取页面内容

java.io.InputStream in = httpurlconnection.getInputStream();

java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, Config.DEFAULT_CHARSET));

String str = breader.readLine();

while (str != null) {

result.append(str);

str = breader.readLine();

}

breader.close();

in.close();

} catch (Exception e) {

} finally {

if (httpurlconnection != null)

httpurlconnection.disconnect();

}

return result.toString().trim();

}

2、httpclient:

public static String post(String url,String params){
HttpClient httpClient = new DefaultHttpClient();

StringBuilder builder = new StringBuilder();

HttpPost post = new HttpPost(url);

try {

if(null!=params){

post.setEntity(new StringEntity(params,"UTF-8"));

}

HttpResponse resp = httpClient.execute(post);

int statusCode = resp.getStatusLine().getStatusCode();

if(statusCode<=304){

HttpEntity entity = resp.getEntity();

if (entity == null) {

throw new IllegalArgumentException("HTTP entity may not be null");

}

if (entity.getContentLength() > Integer.MAX_VALUE) {

throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");

}

int i = (int)entity.getContentLength();

i = i<0 ? 4096 : i;

final InputStream instream = entity.getContent();

final Reader reader = new InputStreamReader(instream, Config.DEFAULT_CHARSET);

final CharArrayBuffer buffer = new CharArrayBuffer(i);

final char[] tmp = new char[1024];

int l;

while((l = reader.read(tmp)) != -1) {

buffer.append(tmp, 0, l);

}

builder.append(buffer);

}

post.abort();

} catch (Exception e) {

post.abort();

}

return builder.toString().trim();

}

② 如何使用java发送post请求

/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(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;
}

③ java 测试post请求 在body里面传递参数怎么设置,怎么接收

package wzh.Http;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(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; } }//函数调用时填入URL和参数(参数非必须)就可以获取返回的数据,发送post请求调用示例String result=HttpRequest.sendPost("/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=","")

④ java HttpPost怎么传递参数

public class HttpURLConnectionPost {

/**

* @param args

* @throws IOException

*/

public static void main(String[] args) throws IOException {

readContentFromPost();

}

public static void readContentFromPost() throws IOException {

// Post请求的url,与get不同的是不需要带参数

URL postUrl = new URL("http://www.xxxxxxx.com");

// 打开连接

HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

// 设置是否向connection输出,因为这个是post请求,参数要放在

// http正文内,因此需要设为true

connection.setDoOutput(true);

// Read from the connection. Default is true.

connection.setDoInput(true);

// 默认是 GET方式

connection.setRequestMethod("POST");

// Post 请求不能使用缓存

connection.setUseCaches(false);

//设置本次连接是否自动重定向

connection.setInstanceFollowRedirects(true);

// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的

// 意思是正文是urlencoded编码过的form参数

connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,

// 要注意的是connection.getOutputStream会隐含的进行connect。

connection.connect();

DataOutputStream out = new DataOutputStream(connection

.getOutputStream());

// 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致

String content = "字段名=" + URLEncoder.encode("字符串值", "编码");

// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面

out.writeBytes(content);

//流用完记得关

out.flush();

out.close();

//获取响应

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line;

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

System.out.println(line);

}

reader.close();

//该干的都干完了,记得把连接断了

connection.disconnect();

}

(4)javapost流扩展阅读:

关于Java HttpURLConnection使用

public static String sendPostValidate(String serviceUrl, String postData, String userName, String password){

PrintWriter out = null;

BufferedReader in = null;

String result = "";

try {

log.info("POST接口地址:"+serviceUrl);

URL realUrl = new URL(serviceUrl);

// 打开和URL之间的连接

URLConnection conn = realUrl.openConnection();

HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;

// 设置通用的请求属性

httpUrlConnection.setRequestProperty("accept","*/*");

httpUrlConnection.setRequestProperty("connection", "Keep-Alive");

httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

httpUrlConnection.setRequestMethod("POST");

httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");

Base64 base64 = new Base64();

String encoded = base64.encodeToString(new String(userName+ ":" +password).getBytes());

httpUrlConnection.setRequestProperty("Authorization", "Basic "+encoded);

// 发送POST请求必须设置如下两行

httpUrlConnection.setDoOutput(true);

httpUrlConnection.setDoInput(true);

// 获取URLConnection对象对应的输出流

out = new PrintWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(),"utf-8"));

// 发送请求参数

out.print(postData);

out.flush();

// 定义BufferedReader输入流来读取URL的响应

in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),"utf-8"));

String line;

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

result += line;

}

//

// if (!"".equals(result)) {

// BASE64Decoder decoder = new BASE64Decoder();

// try {

// byte[] b = decoder.decodeBuffer(result);

// result = new String(b, "utf-8");

// } catch (Exception e) {

// e.printStackTrace();

// }

// }

return result;

} catch (Exception e) {

log.info("调用异常",e);

throw new RuntimeException(e);

}

//使用finally块来关闭输出流、输入流

finally{

try{

if(out!=null){

out.close();

}

if(in!=null){

in.close();

}

}

catch(IOException e){

log.info("关闭流异常",e);

}

}

}

}

⑤ java post 数据,不让页面跳转

有很多种方法:
1.用AJAX模式,这是不刷新页面提交的最好模式,网上很多完整例子,可以参考一下;
2.如果另一个页面只有业务处理功能,不需要界面显示的话,可以先POST数据到此页面处理数据,处理成功后返回到原页(此实现方案会刷新页面)。

⑥ 如何在java中发送post请求

package com.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class D {
public static void main(String[] args){
List<NameValuePair> nvps= new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", "1"));
String url="https://www.hao123.com/";

HttpClient httpClient = null;
String response="";
try {

HttpPost post = new HttpPost(url);
post.setHeader("Connection", "close");

httpClient = new DefaultHttpClient();
post.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse httpres= httpClient.execute(post);

if (httpres.getStatusLine().getStatusCode() >= 300) {
System.out.println("Request Failed,Code:" + httpres.getStatusLine().getStatusCode() + ",URL:" + url);
}

response = EntityUtils.toString(httpres.getEntity(), "utf-8");
}catch(Exception e){

e.printStackTrace();
}finally{
if(httpClient!=null){
httpClient.getConnectionManager().shutdown();
}

}
System.out.println(response);

}
}

需要httpclient-4.1.3.jar,httpcore-4.1.4.jar和commons-logging-1.1.1.jar

⑦ java http post 同时发送文件流与数据

您好,提问者:
首先表单、文件同时发送那么肯定是可以的,关于获取的话很难了,因为发送文件的话form必须设置为:multipart/form-data数据格式,默认为:application/x-www-form-urlencoded表单格式。我们称之为二进制流和普通数据流。

刚才说了<form的entype要改为multipart/form-data才能进行发送文件,那么这个时候你表单的另外数据就也会被当成二进制一起发送到服务端。

获取读取过来的内容如下:

//拿到用户传送过来的字节流
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}

上面如图的代码,我们发现发送过来的表单数据跟文件数据是混乱的,我们根本没办法解析(很麻烦),这个时候我们就需要用到第三方辅助(apache 提供的fileupload.jar)来进行获取。

这个网上有很多代码的,如果有什么不明白可以去自行网络,或者追问,我这里只是给你提供的思路,希望理解,谢谢!

⑧ java程序如何获取POST方式提交的数据

你好,你说的是html或jsp中的表单向服务器中提交请求吧,在Servlet中,你可以直接使用request.getParamter("参数名称") ;就可以接收到对应的参数了。

⑨ java 怎样发送 POST

privatevoidpostMethod(Stringurl)throwsIOException
{
url="http://www.newsmth.net/bbslogin2.php";
PostMethodpostMethod=newPostMethod(url);
//填入各个表单域的值
NameValuePair[]data={newNameValuePair("id","herrapfel"),newNameValuePair("passwd","")};
//将表单的值放入postMethod中
postMethod.setRequestBody(data);
//执行postMethod
intstatusCode=httpClient.executeMethod(postMethod);
System.out.println("statuscode:"+statusCode);
//HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发

if(statusCode==HttpStatus.SC_OK)
{
StringBuffercontentBuffer=newStringBuffer();
InputStreamin=postMethod.getResponseBodyAsStream();
BufferedReaderreader=newBufferedReader(newInputStreamReader(in,postMethod.getResponseCharSet()));
StringinputLine=null;
while((inputLine=reader.readLine())!=null)
{
contentBuffer.append(inputLine);
System.out.println("inputline:"+inputLine);
contentBuffer.append("/n");
}
in.close();
}
elseif(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY)
{
//从头中取出转向的地址
HeaderlocationHeader=postMethod.getResponseHeader("location");
Stringlocation=null;
if(locationHeader!=null)
{
location=locationHeader.getValue();
System.out.println("Thepagewasredirectedto:"+location);
}
else
{
System.err.println("Locationfieldvalueisnull.");
}
}}

阅读全文

与javapost流相关的资料

热点内容
编译怎么学 浏览:329
数码管显示0到9plc编程 浏览:665
服务器是为什么服务的 浏览:765
java定义数据类型 浏览:874
安卓pdf手写 浏览:427
什么是app开发者 浏览:284
android闹钟重启 浏览:101
程序员失职 浏览:518
在云服务器怎么改密码 浏览:586
服务器pb什么意思 浏览:940
51驾驶员的是什么app 浏览:670
php静态变量销毁 浏览:886
编程买苹果电脑 浏览:762
flac算法 浏览:499
reactnative与android 浏览:664
程序员是干什么的工作好吗 浏览:258
kbuild编译ko 浏览:469
条件编译的宏 浏览:566
韩语编程语言 浏览:648
小程序开发如何租用服务器 浏览:82