关于java实现post的信息

博主:adminadmin 2023-01-05 09:42:10 537

本篇文章给大家谈谈java实现post,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java中怎样用post,get,put请求

java中用post,get,put请求方法:

public static String javaHttpGet(String url,String charSet){

String resultData = null;

try {

URL pathUrl = new URL(url); //创建一个URL对象

HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打开一个HttpURLConnection连接

urlConnect.setConnectTimeout(30000); // 设置连接超时时间

urlConnect.connect();

if (urlConnect.getResponseCode() == 200) { //请求成功

resultData = readInputStream(urlConnect.getInputStream(), charSet);

}

} catch (MalformedURLException e) {

LogL.getInstance().getLog().error("URL出错!", e);

} catch (IOException e) {

LogL.getInstance().getLog().error("读取数据流出错!", e);

}

return resultData;

}

public static String javaHttpPost(String url,MapString,Object map,String charSet){

String resultData=null;

StringBuffer params = new StringBuffer();

try {

IteratorEntryString, Object ir = map.entrySet().iterator();

while (ir.hasNext()) {

Map.EntryString, Object entry = (Map.EntryString, Object) ir.next();

params.append(URLEncoder.encode(entry.getKey(),charSet) + "=" + URLEncoder.encode(entry.getValue().toString(), charSet) + "");

}

byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();

URL pathUrl = new URL(url); //创建一个URL对象

HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();

urlConnect.setConnectTimeout(30000); // 设置连接超时时间

urlConnect.setDoOutput(true); //post请求必须设置允许输出

urlConnect.setUseCaches(false); //post请求不能使用缓存

urlConnect.setRequestMethod("POST"); //设置post方式请求

urlConnect.setInstanceFollowRedirects(true);

urlConnect.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset="+charSet);// 配置请求Content-Type

urlConnect.connect(); // 开始连接

DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 发送请求参数

dos.write(postData);

dos.flush();

dos.close();

if (urlConnect.getResponseCode() == 200) { //请求成功

resultData = readInputStream(urlConnect.getInputStream(),charSet);

}

} catch (MalformedURLException e) {

LogL.getInstance().getLog().error("URL出错!", e);

} catch (IOException e) {

LogL.getInstance().getLog().error("读取数据流出错!", e);

} catch (Exception e) {

LogL.getInstance().getLog().error("POST出错!", e);

}

return resultData;

}

java 怎样发送 POST

private void postMethod(String url) throws IOException

 {     

  url = "";

  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.");

      }

  }

 

 

 

 }

如何在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){

ListNameValuePair nvps= new ArrayListNameValuePair();

nvps.add(new BasicNameValuePair("id", "1"));

String url="";

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 发送post请求

/**

* 向指定 URL 发送POST方法的请求

*

* @param url

* 发送请求的 URL

* @param param

* 请求参数,请求参数应该是 name1=value1name2=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利用HttpURLConnection发送post请求上传文件

在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )

先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息

Java代码

public void doPost(HttpServletRequest request HttpServletResponse response)

throws ServletException IOException {

//获取输入流 是HTTP协议中的实体内容

ServletInputStream  in=request getInputStream();

//缓冲区

byte buffer[]=new byte[ ];

FileOutputStream out=new FileOutputStream( d:\\test log );

int len=sis read(buffer );

//把流里的信息循环读入到file log文件中

while( len!= ){

out write(buffer len);

len=in readLine(buffer );

}

out close();

in close();

}

来一个form表单

form name= upform action= upload do method= POST

enctype= multipart/form data

参数input type= text name= username /br/

文件 input type= file name= file /br/

文件 input type= file name= file /br/

input type= submit value= Submit /

br /

/form

假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件 上传后test log里如下

Java代码

da e c

Content Disposition: form data; name= username

hello word

da e c

Content Disposition: form data; name= file ; filename= D:\haha txt

Content Type: text/plain

haha

hahaha

da e c

Content Disposition: form data; name= file ; filename= D:\huhu txt

Content Type: text/plain

messi

huhu

da e c

研究下规律发现有如下几点特征

第一行是 d b bc 作为分隔符 然后是 \r\n 回车换行符 这个 d b bc 分隔符浏览器是随机生成的

第二行是Content Disposition: form data; name= file ; filename= D:\huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)

第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看

然后就是回车换行符

在下就是文件或参数的内容或值了 如 hello word

最后一行是 da e c 注意最后多了二个 ;

有了这些就可以使用HttpURLConnection来实现上传文件功能了

Java代码 public void upload(){

ListString list  = new ArrayListString();  //要上传的文件名 如 d:\haha doc 你要实现自己的业务 我这里就是一个空list

try {

String BOUNDARY = d a d c ; // 定义数据分隔线

URL url = new URL( );

HttpURLConnection conn = (HttpURLConnection) url openConnection();

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

conn setDoOutput(true);

conn setDoInput(true);

conn setUseCaches(false);

conn setRequestMethod( POST );

conn setRequestProperty( connection Keep Alive );

conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );

conn setRequestProperty( Charsert UTF );

conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);

OutputStream out = new DataOutputStream(conn getOutputStream());

byte[] end_data = ( \r\n + BOUNDARY + \r\n ) getBytes();// 定义最后数据分隔线

int leng = list size();

for(int i= ;ileng;i++){

String fname = list get(i);

File file = new File(fname);

StringBuilder *** = new StringBuilder();

*** append( );

*** append(BOUNDARY);

*** append( \r\n );

*** append( Content Disposition: form data;name=\ file +i+ \ ;filename=\ + file getName() + \ \r\n );

*** append( Content Type:application/octet stream\r\n\r\n );

byte[] data = *** toString() getBytes();

out write(data);

DataInputStream in = new DataInputStream(new FileInputStream(file));

int bytes = ;

byte[] bufferOut = new byte[ ];

while ((bytes = in read(bufferOut)) != ) {

out write(bufferOut bytes);

}

out write( \r\n getBytes()); //多个文件时 二个文件之间加入这个

in close();

}

out write(end_data);

out flush();

out close();

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

BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));

String line = null;

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

System out println(line);

}

} catch (Exception e) {

System out println( 发送POST请求出现异常! + e);

e printStackTrace();

}

lishixinzhi/Article/program/Java/hx/201311/27114

如何使用java模拟post请求

你要导入httpclient的jar包,要是你请求参数格式是json的或者返回的是json格式数据,你还需要导入json包

/**

* post请求

* @param url url地址

* @param jsonParam 参数

* @param noNeedResponse 不需要返回结果

* @return

*/

public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){

//post请求返回结果

DefaultHttpClient httpClient = new DefaultHttpClient();

JSONObject jsonResult = null;

HttpPost method = new HttpPost(url);

try {

if (null != jsonParam) {

//解决中文乱码问题

StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");

entity.setContentEncoding("UTF-8");

entity.setContentType("application/json");

method.setEntity(entity);

}

HttpResponse result = httpClient.execute(method);

url = URLDecoder.decode(url, "UTF-8");

/**请求发送成功,并得到响应**/

if (result.getStatusLine().getStatusCode() == 200) {

String str = "";

try {

/**读取服务器返回过来的json字符串数据**/

str = EntityUtils.toString(result.getEntity());

if (noNeedResponse) {

return null;

}

/**把json字符串转换成json对象**/

jsonResult = JSONObject.fromObject(str);

} catch (Exception e) {

logger.error("post请求提交失败:" + url, e);

}

}

} catch (IOException e) {

logger.error("post请求提交失败:" + url, e);

}

return jsonResult;

}

java实现post的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、java实现post的信息别忘了在本站进行查找喔。