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嗎,這個我就沒有研究過了