您的位置:首页 > 理论基础 > 计算机网络

java中用httpClient请求service,httpPost方法示例

2013-12-27 16:57 597 查看
所需jar包:

commons-logging-1.1.1.jar

commons-codec-1.4.jar

httpclient-4.1.2.jar

httpcore-4.1-alpha1.jar

/**

*

* 方法描述:

* @auth:danni

* @date:2013-12-27 下午04:25:07

* @param args

* @return:void

*/

public static void main(String[] args) {

HttpClient httpClient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://test.service.cc");

// timestamp

String timestamp = System.currentTimeMillis() + "";

// 签名

String signature = SHA1.hex_sha1(secretkey + timestamp + username);//用sha1加密

HttpResponse response = null;

try {

JSONObject obj = new JSONObject();

obj.put("username", username);

obj.put("signature", signature);

obj.put("timestamp", timestamp);

System.out.println("TestHttpPost.main()" + obj.toString());

httppost.setEntity(new StringEntity(obj.toString()));

response = httpClient.execute(httppost);

int code = response.getStatusLine().getStatusCode();//成功请求

if (code == 200) {

String rev = EntityUtils.toString(response.getEntity());// 返回json格式:

// {"id":

// "27JpL~j4vsL0LX00E00005","version":

// "abc"}

System.out.println("TestHttpPost.main" + rev);

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: