通常用http的post,儘可能不用get;java
開發中通常都使用org.apache.http的jar包,比較成熟,方便,易用;固然了,直接用Java提供的也行apache
package com.XXXX.XXXX.service;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;數組
/*
* Http接口 post
* 接收下屬客戶端上傳樣本,保存樣本文件
* apache官網能夠下載最新的jar包和demo
* http://hc.apache.org/downloads.cgi
*/
public class TestSampleUpload4client {
public static void main(String[] args) throws ClientProtocolException, IOException{
String url = "http://192.168.1.6:8010/xxxxxxxxxxx/sample/fileUpload.action";
// 配置要 POST 的數據
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 設置爲瀏覽器兼容模式
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 設置請求的編碼格式
multipartEntityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName(HTTP.UTF_8)); 瀏覽器
//設置一致的編碼格式極其重要,不然容易出現亂碼,無論客戶端是以什麼語言什麼方式進行調用,必須讓其編碼格式與接收端一致;
multipartEntityBuilder.addTextBody("userName", "admin",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("psd", "admin",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("mac", "ma2343344f1333",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("md5", "afy67juu8776a",TEXT_PLAIN);
multipartEntityBuilder.addTextBody("type", "sample",TEXT_PLAIN);
//文件路徑
File file = new File("D:\\glpt\\abc.txt");
multipartEntityBuilder.addBinaryBody("file", file);post
/*
* 如下的參數提交方式也行
StringBody userName = new StringBody("admin", ContentType.create(
"text/plain", Consts.UTF_8));
StringBody password = new StringBody("admin", ContentType.create(
"text/plain", Consts.UTF_8));
// 把文件轉換成流對象FileBody
FileBody bin = new FileBody(file);
multipartEntityBuilder.addPart("username", userName);
multipartEntityBuilder.addPart("password", password);
multipartEntityBuilder.addPart("file", bin);
*/
post(url,multipartEntityBuilder);
}
public static void post(String url,MultipartEntityBuilder multipartEntityBuilder) throws ClientProtocolException, IOException{
// 創建HttpPost對象
HttpPost httppost = new HttpPost(url);
HttpClient httpclient = HttpClientBuilder.create().build();
// 生成 HTTP POST 實體
HttpEntity httpEntity = multipartEntityBuilder.build();
httppost.setEntity(httpEntity);
// 發送Post,並返回一個HttpResponse對象
HttpResponse httpResponse = httpclient.execute(httppost);
// 如下兩行能夠獲得指定的Header
// Header header = httpResponse.getFirstHeader("Content-Length");
// String headerVal = header.getValue();
HttpEntity httpEntity2 = httpResponse.getEntity();
System.out.println("httpResponse.getStatusLine().getStatusCode():"+httpResponse.getStatusLine().getStatusCode());
// 若是狀態碼爲200,就是正常返回
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(httpEntity2);
// 獲得返回的字符串
System.out.println(result);
// 若是是下載文件,能夠用response.getEntity().getContent()返回InputStream
}else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
// 若是狀態碼爲302
String locationUrl = httpResponse.getLastHeader("location").getValue();
post(locationUrl,multipartEntityBuilder);
}else {
String result = EntityUtils.toString(httpEntity2);
// 獲得返回的字符串
System.out.println(result);
}
}ui
}編碼
/**url
*另外一種處理方式
* @param args
* @throws UnsupportedEncodingException
* @throws IOException
* @throws ClientProtocolException
public static void main(String[] args) throws ClientProtocolException, IOException{
// TODO Auto-generated method stub
// POST的URL
String url = "http://192.168.10.203:8010/manageplatform/sample/sampleUpload.action";
// 創建HttpPost對象
HttpPost httppost = new HttpPost(url);
// 創建一個NameValuePair數組,用於存儲欲傳送的參數
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加參數
params.add(new BasicNameValuePair("userName", "admin"));
params.add(new BasicNameValuePair("psd", "admin"));
params.add(new BasicNameValuePair("mac", "mac3333333333"));
params.add(new BasicNameValuePair("md5", "md5555555555"));
params.add(new BasicNameValuePair("type", "sample"));
HttpClient httpclient = new DefaultHttpClient();
// 設置編碼
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 發送Post,並返回一個HttpResponse對象
HttpResponse httpResponse = httpclient.execute(httppost);
// 如下兩行能夠獲得指定的Header
Header header = httpResponse.getFirstHeader("Content-Length");
String headerVal = header.getValue();
HttpEntity httpEntity = httpResponse.getEntity();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 若是狀態碼爲200,就是正常返回
String result = EntityUtils.toString(httpEntity);
// 獲得返回的字符串
System.out.println(result);
// 打印輸出
// 若是是下載文件,能夠用response.getEntity().getContent()返回InputStream
}else {
String result = EntityUtils.toString(httpEntity);
// 獲得返回的字符串
System.out.println(result);
}
}
*/
}.net
以上例子中http請求了一個url:http://192.168.10.xxx:8010/xxxxxxxx/sample/sampleUpload.action;日誌
其中sampleUpload.action是用struts配置的;sampleUpload.action對應的action方法以下:
/**
* HTTP接口,
* 接收下屬客戶端及子管理中心上傳樣本,保存樣本文件
*
* @return */ public void sampleUpload() { OutputStream out = null; try { out = sResponse.getOutputStream(); String result = "Response=101;"; String path = sRequest.getSession().getServletContext().getRealPath("/"); System.out.println(path); //用戶認證 String userName = sRequest.getParameter("userName"); String psd = sRequest.getParameter("psd"); //此處省略了用戶權限認證的操做; String md5 = sRequest.getParameter("md5"); String mac = sRequest.getParameter("mac"); String type = sRequest.getParameter("type"); String ip = sRequest.getRemoteAddr(); if (StringUtils.isEmpty(md5) || StringUtils.isEmpty(mac) || StringUtils.isEmpty(type)) { result = "Response=011;"; } else { for (int i = 0; i < fileFileName.size(); i++) { try { String filename = fileFileName.get(i); String savePath = StringUtils.isEmpty(UrlAddress.getUrl(type)) ? path + "WEB-INF/uploadPath/" + type : UrlAddress.getUrl(type); if (!new File(savePath).exists()) { new File(savePath).mkdirs(); } filename = savePath + "/" + filename; // sampleName = fileFileName.get(i); FileOutputStream fos = new FileOutputStream(filename); InputStream is = new FileInputStream(file.get(i)); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); filename = filename.replace('\\', '/'); result = "Response=000;"; result = sampleService.sampleUpload(type, md5, mac, filename, ip); } catch (Exception e) { result = "Response=101;"; e.printStackTrace(); } } } //記錄接口日誌 sampleService.interfaceLogSave("1", mac, md5, ip, result); //返回操做結果 out.write(result.getBytes()); out.flush(); } catch (IOException e1) { e1.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } }