java模拟post上传文件
⑴ 怎么使用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;
⑵ 求java模拟post上传任意类型文件代码
http://hi..com/garry1861/blog/category/Ssh 我这里面写的很详细,你可以看看。名称是struts2 上传文件 你看看就OK了
⑶ java后台post方法上传文件
/** * 执行post请求并将返回内容转为json格式返回 */public static JsonObject doPost(String url, JsonObject message)throws WeiXinException {JsonObject jo = null;PrintWriter out = null;InputStream in = null;try {if (url.startsWith("https")){//https方式提交需要SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.connect();in = conn.getInputStream();}else{in = new URL(url).openStream();}// 打开和URL之间的连接URLConnection conn = new URL(url).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(message.toString());// flush输出流的缓冲out.flush();// POST请求out.flush();out.close();in = conn.getInputStream();jo = JSON.parse(getContext(in));doExeption(jo);} catch (MalformedURLException e) {e.printStackTrace();} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} finally {if (out != null) {out.flush();out.close();}if (in != null ){try {in.close();} catch (IOException e) {e.printStackTrace();}}}return jo;}
⑷ 如何使用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提交
String action = "xxxxxxxxxxx";
URL url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setConnectTimeout(0);
http.setInstanceFollowRedirects(true);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDefaultUseCaches(false);
http.setDoOutput(true);
String queryString = "";
PrintWriter out = new PrintWriter(http.getOutputStream());
out.print(queryString);//传入参数
out.close();
http.connect();//连接
InputStream in = httpURLConnection.getInputStream();//返回流
其他的自己来了吧
⑹ java发送post请求传送文本和文件
kankan
⑺ 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中怎样上传文件
Java代码实现文件上传
FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件读入
StringfilePath=request.getRealPath(fileAddre);//取系统当前路径
Filefile1=newFile(filePath);//添加了自动创建目录的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一个上传文件的输出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//将文件写入服务器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
⑼ 关于JAVA模拟发送post请求并响应内容
如果你是用java的api实现的模拟post请求,那么你需要在你之前构造的http request的header里加上
Cookie:名字=值 然后统一包装成你的conenction的OutputStream。
建议你用apache的HttpClient api项目,里面有专门处理cookie的api,这样事情就简单许多。
⑽ java中用一段代码模拟post提交文件后,再写个java程序接收这个文件,高分急求,坐等
在JAVA里面模拟HTTP访问可以使用很多开源的框架,apache的httpclient就很好用,可以模拟使用GET和POST提交方式,至于PHP吗,这个我就没有研究过了