httppostjava
‘壹’ 如何使用java模拟post请求
两种选择:一、使用httpclient,二使用java自带的类库。
1、java自带类库:
public static String call(String address,String params) {
URL url = null;
HttpURLConnection httpurlconnection = null;
StringBuilder result = new StringBuilder();
try {
url = new URL(address);
// 以post方式请求
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
if(null!=params&¶ms.length()>0){
httpurlconnection.getOutputStream().write(params.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
}
// 获取页面内容
java.io.InputStream in = httpurlconnection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, Config.DEFAULT_CHARSET));
String str = breader.readLine();
while (str != null) {
result.append(str);
str = breader.readLine();
}
breader.close();
in.close();
} catch (Exception e) {
} finally {
if (httpurlconnection != null)
httpurlconnection.disconnect();
}
return result.toString().trim();
}
2、httpclient:
public static String post(String url,String params){
HttpClient httpClient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpPost post = new HttpPost(url);
try {
if(null!=params){
post.setEntity(new StringEntity(params,"UTF-8"));
}
HttpResponse resp = httpClient.execute(post);
int statusCode = resp.getStatusLine().getStatusCode();
if(statusCode<=304){
HttpEntity entity = resp.getEntity();
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
i = i<0 ? 4096 : i;
final InputStream instream = entity.getContent();
final Reader reader = new InputStreamReader(instream, Config.DEFAULT_CHARSET);
final CharArrayBuffer buffer = new CharArrayBuffer(i);
final char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
builder.append(buffer);
}
post.abort();
} catch (Exception e) {
post.abort();
}
return builder.toString().trim();
}
‘贰’ 怎么用java模拟浏览器提交html页面的表单数据
httpclient就行了,给你个取IP的例子好了
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class IPHelper {
public String getSourceText(String ip) throws IOException {
String text = null;
HttpClient client = new HttpClient();
client.getParams().setContentCharset("GBK");
PostMethod post = new PostMethod("http://www.ip138.com/ips8.asp");
NameValuePair[] data = { new NameValuePair("action", "2"),
new NameValuePair("ip", ip) };
post.setRequestBody(data);
client.executeMethod(post);
text = post.getResponseBodyAsString();
post.releaseConnection();
return text;
}
public static void main(String[] args) throws IOException {
IPHelper h=new IPHelper();
System.out.println(h.getSourceText("192.169.0.1"));
}
}
这个是Post的,还有Get的,看你的form是怎么样的了。
‘叁’ java HttpPost怎么传递参数
public class HttpURLConnectionPost {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
readContentFromPost();
}
public static void readContentFromPost() throws IOException {
// Post请求的url,与get不同的是不需要带参数
URL postUrl = new URL("http://www.xxxxxxx.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// 默认是 GET方式
connection.setRequestMethod("POST");
// Post 请求不能使用缓存
connection.setUseCaches(false);
//设置本次连接是否自动重定向
connection.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
String content = "字段名=" + URLEncoder.encode("字符串值", "编码");
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
out.writeBytes(content);
//流用完记得关
out.flush();
out.close();
//获取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
//该干的都干完了,记得把连接断了
connection.disconnect();
}
(3)httppostjava扩展阅读:
关于Java HttpURLConnection使用
public static String sendPostValidate(String serviceUrl, String postData, String userName, String password){
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
log.info("POST接口地址:"+serviceUrl);
URL realUrl = new URL(serviceUrl);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
// 设置通用的请求属性
httpUrlConnection.setRequestProperty("accept","*/*");
httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
Base64 base64 = new Base64();
String encoded = base64.encodeToString(new String(userName+ ":" +password).getBytes());
httpUrlConnection.setRequestProperty("Authorization", "Basic "+encoded);
// 发送POST请求必须设置如下两行
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(),"utf-8"));
// 发送请求参数
out.print(postData);
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
//
// if (!"".equals(result)) {
// BASE64Decoder decoder = new BASE64Decoder();
// try {
// byte[] b = decoder.decodeBuffer(result);
// result = new String(b, "utf-8");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
return result;
} catch (Exception e) {
log.info("调用异常",e);
throw new RuntimeException(e);
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException e){
log.info("关闭流异常",e);
}
}
}
}
‘肆’ 如何来 发送HTTP请求GET / POST在Java中
在Java中发送HTTP请求,主要涉及到请求行的构建。请求行由三个部分组成:请求方法字段、URL字段和HTTP协议版本字段,这三个字段之间用空格分隔。例如,使用GET方法访问某个HTML页面时,请求行可以表示为"GET /index.html HTTP/1.1"。这里,"GET"是请求方法,"/index.html"是访问的资源路径,而"HTTP/1.1"则指定了使用的HTTP版本。
除了GET方法外,HTTP协议还支持其他几种请求方法,包括POST、HEAD、PUT、DELETE、OPTIONS、TRACE和CONNECT。其中,POST方法通常用于向服务器发送数据,例如提交表单或上传文件;而HEAD方法则只获取响应头,不获取响应体;PUT方法用于上传数据到服务器,相当于文件上传;DELETE方法则是用于删除服务器上的资源;OPTIONS方法用于获取服务器的许可信息,如支持的请求方法;TRACE方法用于回显客户端发送的请求,主要用于诊断;而CONNECT方法则是用于建立代理连接。
Java中发送HTTP请求的方法有很多,比如使用HttpURLConnection类或第三方库如Apache HttpClient和OkHttp。以HttpURLConnection为例,首先需要创建一个URL对象,然后通过该对象获取HttpURLConnection实例,接下来设置请求方法、添加请求头等,最后执行请求并获取响应。而使用第三方库时,初始化和设置则更加灵活,可以根据需求选择合适的库进行操作。
对于GET请求,HttpURLConnection的使用相对简单。以下是一个使用HttpURLConnection发送GET请求的例子:
java
URL url = new URL("http://example.com/index.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("Failed : HTTP error code : " + responseCode);
}
通过这段代码,你可以看到如何通过HttpURLConnection发送GET请求并处理响应。当然,实际应用中可能还需要处理更复杂的情况,比如添加请求头、处理异常等。
对于POST请求,基本步骤类似,只是需要设置请求方法为POST,并且通常需要设置请求体。以下是一个简单的POST请求示例:
java
URL url = new URL("http://example.com/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "param1=value1¶m2=value2";
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(data);
}
这段代码展示了如何通过HttpURLConnection发送POST请求,并设置请求体。同样,实际应用中可能需要添加更多细节,如处理响应、添加更多请求头等。
总之,Java中发送HTTP请求GET和POST方法的实现方式多样,可以根据具体需求选择合适的库和方法。无论使用哪种方式,都需要正确设置请求方法、URL、请求头等,才能确保请求的成功发送和响应的正确处理。
‘伍’ java 接口调用,根据接口文档写测试,用post方法,刚怎么做啊,有个完整的例子么
可使用android自带的httpclient框架实现。
1. GET 方式传递参数
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "数据")); //增加参数1
params.add(new BasicNameValuePair("param2", "value2"));//增加参数2
String param = URLEncodedUtils.format(params, "UTF-8");//对参数编码
String baseUrl = "服务器接口完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//将URL与参数拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2. POST方式 方式传递参数
//和GET方式一样,先将参数放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加参数1
params.add(new BasicNameValuePair("param2", "第二个参数"));//增加参数2
try {
HttpPost postMethod = new HttpPost(baseUrl);//创建一个post请求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //执行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
‘陆’ java http post 同时发送文件流与数据
您好,提问者:
首先表单、文件同时发送那么肯定是可以的,关于获取的话很难了,因为发送文件的话form必须设置为:multipart/form-data数据格式,默认为:application/x-www-form-urlencoded表单格式。我们称之为二进制流和普通数据流。
刚才说了<form的entype要改为multipart/form-data才能进行发送文件,那么这个时候你表单的另外数据就也会被当成二进制一起发送到服务端。
获取读取过来的内容如下:
//拿到用户传送过来的字节流
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
上面如图的代码,我们发现发送过来的表单数据跟文件数据是混乱的,我们根本没办法解析(很麻烦),这个时候我们就需要用到第三方辅助(apache 提供的fileupload.jar)来进行获取。
这个网上有很多代码的,如果有什么不明白可以去自行网络,或者追问,我这里只是给你提供的思路,希望理解,谢谢!