java实现post get 传参数url

本文介绍了一个使用Apache HttpClient库实现GET和POST请求的具体示例。通过示例代码展示了如何配置HTTP客户端,发送GET请求获取资源,并通过POST方法提交数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 
 */
package com.byzk.p2p.thread;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import  org.apache.commons.httpclient.*;
import  org.apache.commons.httpclient.methods.*;
import  org.apache.commons.httpclient.params.HttpMethodParams;
/*** <p>Title:HttpClientTest </p>
* <p>Description:使用httpClient 包 实现post get 提交 </p>
* <p>Company:xbd </p>
* @author:Administrator
* @date:2016年11月7日上午11:53:10 */
public class HttpClientTest {


/**

* <p>Description:get 请求方式连接 </p>
* <p>Company:xbd </p>
* @author:lilei
* @date:2016年11月7日下午12:31:48
*/
public void GetTest(String url) {


HttpClient httpclient = new HttpClient();
// 创建get实例
GetMethod getmethod = new GetMethod(url);
getmethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try {
// 执行getMethod
int statucode = httpclient.executeMethod(getmethod);
if (statucode != HttpStatus.SC_OK) {
System.err.println("method failed" + getmethod.getStatusLine());
}


// 读取内容
byte[] responseBody = getmethod.getResponseBody();
// 处理内容
System.out.println(new String(responseBody));
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
getmethod.releaseConnection();
}


}

public void postTest(String url) {


HttpClient httpclient = new HttpClient();
         //初始化post
PostMethod postmethod = new PostMethod(url);


List<NameValuePair> list = new ArrayList<NameValuePair>();


NameValuePair pair = new NameValuePair("user_id", "1213");


list.add(pair);


postmethod.setRequestBody((NameValuePair[]) list.toArray());
//执行postmethod
try {
int statuCode = httpclient.executeMethod(postmethod);
if(statuCode == HttpStatus.SC_MOVED_PERMANENTLY || statuCode == HttpStatus.SC_MOVED_TEMPORARILY){

Header header = postmethod.getRequestHeader("location");
String location="";
if(header!=null){
location = header.getValue();
System.out.println("the page was redirect to "+ location);
}else{
System.out.println("location value is null");
}
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值