HttpClient 3.1
Get 和 Post 基本操作
public static String doGet(String url) {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
try {
return executeMethod(client, method);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String doPost(String url, RequestEntity entity) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
try {
method.setRequestEntity(entity);
return executeMethod(client, method);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String executeMethod(HttpClient client, HttpMethod method) throws IOException {
int state = client.executeMethod(method);
StringBuilder stringBuilder = new StringBuilder();
if (state == HttpStatus.SC_OK) {
InputStream is = method.getResponseBodyAsStream();
byte[] bytes = new byte[1024];
while (is.read(bytes) != -1) {
stringBuilder.append(new String(bytes));
}
return stringBuilder.toString();
}
return null;
}
RequestEntity
- StringRequestEntity
- ByteArrayRequestEntity
- MultipartRequestEntity
- FileRequestEntity
- InputStreamRequestEntity
请求Content-type 为 application/x-www-form-urlencoded
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://localhost:8083/type");
method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
NameValuePair typeId = new NameValuePair("typeId","5");
NameValuePair name = new NameValuePair("name","type1");
NameValuePair sum = new NameValuePair("sum","500");
NameValuePair[] pairs = {typeId,name,sum};
method.setRequestBody(pairs);
try {
client.executeMethod(method);
} catch (IOException e) {
e.printStackTrace();
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。