HttpClient發送Post和Get請求

post請求方法和get請求方法java

 

package com.xkeshi.paymentweb.controllers.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* Created by jiangzw on 2017/11/3.
*/
public class MyTestHttpClient {

/**
* post方式提交表單(模擬用戶登陸請求)
*/
public static void doFormPost() {
// 建立默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立httppost
String url = "http://localhost:8888/myTest/testHttpClientPost";
HttpPost httppost = new HttpPost(url);
// 建立參數隊列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(entity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉鏈接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 發送 get請求
*/
public static void doGet() {
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立參數隊列
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));

try {
//參數轉換爲字符串
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
String url = "http://localhost:8888/myTest/testHttpClientGet" + "?" + paramsStr;
// 建立httpget.
HttpGet httpget = new HttpGet(url);
System.out.println("executing request " + httpget.getURI());
// 執行get請求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 獲取響應實體
HttpEntity entity = response.getEntity();
// 打印響應狀態
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印響應內容長度
System.out.println("Response content length: " + entity.getContentLength());
// 打印響應內容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉鏈接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* post方式提交表單(模擬用戶登陸請求)
*/
public static void doStringPost() {
// 建立默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立httppost
String url = "http://localhost:8888/myTest/testHttpClientStringPost";
HttpPost httppost = new HttpPost(url);
// 建立參數字符串
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
try {
//設置實體內容的格式。APPLICATION_JSON = "application/json",
// 若是傳送"application/xml"格式,選擇ContentType.APPLICATION_XML
StringEntity entity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);
httppost.setEntity(entity); //發送字符串參數
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉鏈接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 上傳文件
*/
public static void doUploadPost() {
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "http://localhost:8888/myTest/testHttpClientUploadPost";
try {
HttpPost httppost = new HttpPost(url);

FileBody fileBody = new FileBody(new File("D:\\img8.jpg"));
StringBody stringBody = new StringBody("一張測試圖片", ContentType.TEXT_PLAIN.withCharset("UTF-8"));

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);//文件參數
builder.addPart("explain", stringBody);//字符串參數
HttpEntity entity = builder.build();

httppost.setEntity(entity);

System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
// doFormPost();
// doGet();
// doStringPost();
doUploadPost();
}

}



處理請求的方法

package com.xkeshi.paymentweb.controllers.test;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.commons.CommonsMultipartFile;import java.io.File;/** * Created by jiangzw on 2017/11/3. */@Controller@RequestMapping(value = "/myTest")public class MyTestController {    @ResponseBody    @RequestMapping(value = "/testHttpClientPost", method = RequestMethod.POST)    public String testHttpClientPost(@RequestParam("username") String username,                                     @RequestParam("password") String password) {        String result = null;        if ("admin".equals(username) && "123456".equals(password)) {            result = "用戶名和密碼驗證成功!";        } else {            result = "用戶名和密碼驗證失敗!";        }        return result;    }    @ResponseBody    @RequestMapping(value = "/testHttpClientGet", method = RequestMethod.GET)    public String testHttpClientGet(@RequestParam("username") String username,                                    @RequestParam("password") String password) {        String result = null;        if ("admin".equals(username) && "123456".equals(password)) {            result = "用戶名和密碼驗證成功!";        } else {            result = "用戶名和密碼驗證失敗!";        }        return result;    }    @ResponseBody    @RequestMapping(value = "/testHttpClientStringPost", method = RequestMethod.POST)    public String testHttpClientStringPost(@RequestBody String requestBody) {        JSONObject jsonObject = JSON.parseObject(requestBody);        String username = jsonObject.get("username").toString();        String password = jsonObject.get("password").toString();        String result = null;        if ("admin".equals(username) && "123456".equals(password)) {            result = "用戶名和密碼驗證成功!";        } else {            result = "用戶名和密碼驗證失敗!";        }        return result;    }    @ResponseBody    @RequestMapping(value = "/testHttpClientUploadPost", method = RequestMethod.POST)    public String testHttpClientUploadPost(@RequestParam("file") CommonsMultipartFile file,                                           @RequestParam("explain") String explain) {        System.out.println("explain: " + explain);        String result = "上傳失敗";        //文件保存路徑和名稱        String savePath = "D:\\home" + File.separator + System.currentTimeMillis() + file.getOriginalFilename();        File newFile= null;        try {            newFile = new File(savePath);            //經過CommonsMultipartFile的方法直接寫文件(注意這個時候)            file.transferTo(newFile);            result = "上傳成功";        } catch (Exception e) {            e.printStackTrace();        }        return result;    }}
相關文章
相關標籤/搜索