A. 如何向http发送post参数
给http post传参,参考以下二个实例: //serverURL url地址 HttpPost httpPost = new HttpPost(serverURL); //param 为参数 StringEntity entity = new StringEntity(param); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost);还可以用map作为参数 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); if(param!=null){ Set set = param.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = param.get(key); formparams.add(new BasicNameValuePair(key.toString(), value.toString())); } }
B. HttpHelper上传文件同时还要POST其他参数,怎么解决
定义一个boundary
stringboundary="——httpboundary";
然后用下面的代码来加字符串参数
StringBuilders=newStringBuilder();s.Append("–").Append(boundary).Append("");s.Append("Content-Disposition:form-data;name="a"11111111111111");s.Append("–").Append(boundary).Append("");s.Append("Content-Disposition:form-data;name="b"222222");AppendString(s.ToString());–把该段字符串加入主byte[]
把以上的字符串s转成byte[]接着用下面的代码把stream转成byte[],并加个上面的byte[]中
s.Append("–").Append(boundary).Append("");s.Append("Content-Disposition:form-data;name="d";filename="ddddd"");s.Append("Content-Type:application/octet-stream");AppendString(s.ToString());–把该段字符串加入主byte[]StreamS=HttpContext.Current.Request.InputStream;byte[]b=newbyte[S.Length];S.Read(b,0,b.Length);AppendBytes(b);–把stream加入主byte[]AppendString("");s.Append("–").Append(boundary).Append("–");s.Append("");–结束主byte[]
然后把上面得到的byte[]写入PostdataByte中,并修改ContentType= "multipart/form-data; boundary=————httpboundary";代码如下:
Method="POST",PostDataType=PostDataType.Byte,PostdataByte=主byte[],ContentType="multipart/form-data;boundary=——httpboundary",ResultType=ResultType.String
C. 怎么使用 HTTP GET 和 POST 传递参数
POST 传递数据 : 创建一个 HttpPost 对象, 使用要连接的uri 创建, 参数放在一个 NameValuePair 数组中, 这个很重要, 这个NameValuePair 可以直接存放要传递的键值对;
D. Android中使用HttpPost实现数据与文件同时上传的功能
第一步:编写一个Servlet,把接收到的HTTP信息保存在一个文件中,代码如下: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取输入流,是HTTP协议中的实体内容 ServletInputStream sis=request.getInputStream(); //缓冲区 byte buffer[]=new byte[1024]; FileOutputStream fos=new FileOutputStream("d://file.log"); int len=sis.read(buffer, 0, 1024); //把流里的信息循环读入到file.log文件中 while( len!=-1 ) { fos.write(buffer, 0, len); len=sis.readLine(buffer, 0, 1024); } fos.close(); sis.close(); } 第二步:实现如下图1的的表单页面,生成一个注册表单,提交到Servlet中详细的代码如下: <form action="servlet/ReceiveFile" method="post" enctype="multipart/form-data"> 第一个参数<input type="text" name="name1"/> <br/> 第二个参数<input type="text" name="name2"/> <br/> 第一个上传的文件<input type="file" name="file1"/> <br/> 第二个上传的文件<input type="file" name="file2"/> <br/> <input type="submit" value="提交"></form>注意了,由于要上传附件,所以一定要设置enctype为multipart/form-data,才可以实现附件的上传。 第三步:填写完信息后按“提交”按钮后,在D盘下查找file.log文件用记事本打开,数据如下:—————————–7d92221b604bcContent-Disposition: form-data; name="name1" hello—————————–7d92221b604bcContent-Disposition: form-data; name="name2" world—————————–7d92221b604bcContent-Disposition: form-data; name="file1"; filename="C:/2.GIF"Content-Type: image/gif GIF89a
E. 怎么给http post添加参数
给http post传参,参考以下二个实例: //serverURL url地址 HttpPost httpPost = new HttpPost(serverURL); //param 为参数 StringEntity entity = new StringEntity(param); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost);还可以用map作为参数 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); if(param!=null){ Set set = param.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = param.get(key); formparams.add(new BasicNameValuePair(key.toString(), value.toString())); } }
F. 我使用httpclient的httpPost,用MultipartEntiy来实现即上传文件也上传参数
后台,试试用struts,可以方便得到前面传送的数据的
G. 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();
}
(7)httppost同时传文件和参数扩展阅读:
关于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);
}
}
}
}
H. http如何实现同时发送文件和报文(用java实现)
这个算是web项目中的文件上传功能接口。
java的web项目现在可以使用idea编辑器创建spring boot项目快回速构建答。(很简单,具体步骤请网络)
文件上传功能也网络吧,一大堆。关键词: spring boot 文件上传
I. 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)来进行获取。
这个网上有很多代码的,如果有什么不明白可以去自行网络,或者追问,我这里只是给你提供的思路,希望理解,谢谢!
J. httpclient如何一起上传内容和图片
以文件的形式传参/** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param actionUrl 访问的服务器URL * @param params 普通参数 * @param files 文件参数 * @return * @throws IOException */ public static void post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "–", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(5 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); InputStream in = null; // 发送文件数据 if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); // name是post中传参的键 filename是文件的名称 sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); if (res == 200) { in = conn.getInputStream(); int ch; StringBuilder sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); } // return in.toString(); }以数据流的形式传参public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files) throws Exception { StringBuilder sb2 = null; String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "–", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(6 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); InputStream in = null; // 发送文件数据 if (files != null) { for (Map.Entry<String, byte[]> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); // InputStream is = new FileInputStream(file.getValue()); // byte[] buffer = new byte[1024]; // int len = 0; // while ((len = is.read(buffer)) != -1) // { // outStream.write(buffer, 0, len); // } // is.close(); outStream.write(file.getValue()); outStream.write(LINEND.getBytes()); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); if (res == 200) { in = conn.getInputStream(); int ch; sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } System.out.println(sb2.toString()); } outStream.close(); conn.disconnect(); // 解析服务器返回来的数据 return ParseJson.getEditMadIconResult(sb2.toString()); } else { return "Update icon Fail"; } // return in.toString(); }