HttpClient发送GET和POST请求

[quote]工作中经常使用的HTTP请求方法,和大家分享下。
package com.pinkitec.core.util;

import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.pinkitec.core.io.unsync.UnsyncByteArrayInputStream;

public class HttpClientUtil {


@SuppressWarnings("deprecation")
public static JSONObject doPost(JSONObject json, String url)throws Exception{

org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setContentChunked(true);

postMethod.setRequestBody(new UnsyncByteArrayInputStream(json.toString().getBytes("UTF-8")));

HttpClientParams params = new HttpClientParams();
params.setConnectionManagerTimeout(10000L);
httpClient.setParams(params);

// 执行postMethod
JSONObject result = null;
int statusCode = 0;
statusCode = httpClient.executeMethod(postMethod);
// 200
if (statusCode == HttpStatus.SC_OK){
result = new JSONObject();

String str = "";
try {
byte[] bytes = postMethod.getResponseBody();
str = new String(bytes, "UTF-8");
JSONObject response = JSONObject.fromObject(str);

return response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
}
postMethod.releaseConnection();
return result;
}



public static JSONObject doGet(JSONObject json, String url)throws Exception{

org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
GetMethod getMethod = new GetMethod(url);


HttpClientParams params = new HttpClientParams();
params.setConnectionManagerTimeout(10000L);

httpClient.setParams(params);

// 执行postMethod
JSONObject result = null;
int statusCode = 0;
statusCode = httpClient.executeMethod(getMethod);
// 200
if (statusCode == HttpStatus.SC_OK){
result = new JSONObject();

String str = "";
try {
byte[] bytes = getMethod.getResponseBody();
str = new String(bytes, "UTF-8");
JSONObject response = JSONObject.fromObject(str);

return response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
}
getMethod.releaseConnection();
return result;
}

public static void main(String[] args) {

String[] a = new String[]{"3","1"};

System.out.println(a.clone());

System.out.println(Float.parseFloat("0.0"));


}


}
[/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值