1. 程式人生 > >使用Httpclient(post請求)上傳檔案及其他引數到https協議的伺服器

使用Httpclient(post請求)上傳檔案及其他引數到https協議的伺服器

最近有一個需求要用到httpclient大概如下:
   運用httpclient傳送請求到一個https的伺服器,其中一個引數就是一個xml檔案,也就是需要把檔案傳上去,
而且有其他的引數,如果用普通的httpclient會報錯如下:(需要證書)
     unable to find valid certification path to requested targe


我們改成用 SSLClient 繼承 DefaultHttpClient來避免使用證書
(可以直接粘過去用)
public class SSLClient extends DefaultHttpClient {
	public SSLClient() throws Exception {
		super();
		SSLContext ctx = SSLContext.getInstance("TLS");
		X509TrustManager tm = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		ctx.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		ClientConnectionManager ccm = this.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", 443, ssf));
	}
}
下面這種方式可以正常使用了,程式碼如下:
public static HttpResult doPostupload(File file, int type, String url) {
    HttpClient httpClient = null;
    HttpPost httpPost = null;

     // 把檔案轉換成流物件FileBody
    FileBody bin = new FileBody(file);
    HttpResult httpResult = null;
    try {
         //***************注意這裡的程式碼******
        httpClient = new SSLClient();
        httpPost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
      //封裝其他引數到Stringbody(需要把int轉成String再放入)
        StringBody username = new StringBody("張三");
        StringBody password = new StringBody("123456");
        StringBody type1 = new StringBody(String.valueOf(type));//type為int 
      //引數放入請求實體(包括檔案和其他引數)
        reqEntity.addPart("config_xml", bin);
        reqEntity.addPart("type", type1);
        reqEntity.addPart("username", username);
        reqEntity.addPart("password", password);
  
        httpPost.setEntity(reqEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        httpResult = convertToHttpResult(httpPost, httpResponse);

          //String body = result.getResponseString(); // body即為伺服器返回的內容

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return httpResult;
}