当前位置:首页 » 编程语言 » java调用post接口

java调用post接口

发布时间: 2024-12-12 12:10:26

1. java应用的post请求怎么实现

在Java应用中实现POST请求,通常有两种主流方法:通过URLConnection类和使用Apache HttpClient库。

使用URLConnection类发送POST请求,是基于Java标准库的功能。通过创建一个URL对象,然后通过其openConnection方法获取一个URLConnection实例,最后利用这个实例的setRequestMethod方法设置请求方式为POST,并通过setEntity方法设置请求体。然后调用其connect方法发起请求,最后读取响应信息。

而Apache HttpClient库的使用,则提供了一种更高级、更灵活的方式实现POST请求。通过创建HttpClient实例,使用其创建Post方法生成HttpPost对象,设置请求头如Content-Type等,再设置请求体,然后调用HttpClient实例的execute方法发起请求。最后读取并处理响应结果。

在实际开发中,选择哪种方法,主要取决于项目需求、团队习惯和对代码可维护性的考量。URLConnection适合轻量级应用,而Apache HttpClient适合对并发、异步操作有较高要求的场景。

2. java中怎样用post,get,put请求

java中用post,get,put请求方法:
public static String javaHttpGet(String url,String charSet){

String resultData = null;
try {
URL pathUrl = new URL(url); //创建一个URL对象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打开一个HttpURLConnection连接
urlConnect.setConnectTimeout(30000); // 设置连接超时时间
urlConnect.connect();
if (urlConnect.getResponseCode() == 200) { //请求成功
resultData = readInputStream(urlConnect.getInputStream(), charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出错!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("读取数据流出错!", e);
}
return resultData;
}
public static String javaHttpPost(String url,Map<String,Object> map,String charSet){
String resultData=null;
StringBuffer params = new StringBuffer();
try {
Iterator<Entry<String, Object>> ir = map.entrySet().iterator();
while (ir.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) ir.next();
params.append(URLEncoder.encode(entry.getKey(),charSet) + "=" + URLEncoder.encode(entry.getValue().toString(), charSet) + "&");
}
byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();
URL pathUrl = new URL(url); //创建一个URL对象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();
urlConnect.setConnectTimeout(30000); // 设置连接超时时间
urlConnect.setDoOutput(true); //post请求必须设置允许输出
urlConnect.setUseCaches(false); //post请求不能使用缓存
urlConnect.setRequestMethod("POST"); //设置post方式请求
urlConnect.setInstanceFollowRedirects(true);
urlConnect.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset="+charSet);// 配置请求Content-Type
urlConnect.connect(); // 开始连接
DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 发送请求参数
dos.write(postData);
dos.flush();
dos.close();
if (urlConnect.getResponseCode() == 200) { //请求成功
resultData = readInputStream(urlConnect.getInputStream(),charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出错!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("读取数据流出错!", e);
} catch (Exception e) {
LogL.getInstance().getLog().error("POST出错!", e);
}
return resultData;
}

3. java语言使用post方式调用webService方式

WebService可以有Get、Post、Soap、Document四种方式调用,以下Java通过post方式调用WebService代码:

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.OutputStreamWriter;
importjava.net.URL;
importjava.net.URLConnection;
importjava.net.URLEncoder;
importorg.apache.cxf.endpoint.Client;
importorg.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
/**
*功能描述:WebService调用
*
*/
publicclassClientTest{
/**
*功能描述:HTTP-POST
*
*/
publicStringpost(){
OutputStreamWriterout=null;
StringBuildersTotalString=newStringBuilder();
try{
URLurlTemp=newURL(
"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity");
URLConnectionconnection=urlTemp.openConnection();
connection.setDoOutput(true);
out=newOutputStreamWriter(connection.getOutputStream(),"UTF-8");
StringBuffersb=newStringBuffer();
sb.append("byProvinceName=福建");
out.write(sb.toString());
out.flush();
StringsCurrentLine;
sCurrentLine="";
InputStreaml_urlStream;
l_urlStream=connection.getInputStream();//请求
BufferedReaderl_reader=newBufferedReader(newInputStreamReader(
l_urlStream));
while((sCurrentLine=l_reader.readLine())!=null){
sTotalString.append(sCurrentLine);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
if(null!=out){
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnsTotalString.toString();
}
}

4. 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();
}

5. 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();

}

(5)java调用post接口扩展阅读:

关于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);

}

}

}

}

6. java http post 怎么设置 raw格式

调试微信推广支持中二维码生成api的接口,使用chrome浏览器的postman插件,post请求时有一个选项是form-data,或者raw,使用raw可以请求成功,from-data不知道怎么组装key和value所以一直失败。非常不明白raw是什么意思,google网络都没有相关的解释。后来研究发现,其实raw方式使用的是纯字符串的数据上传方式,所以在POST之前,可能需要手工的把一些json/text/xml格式的数据转换成字符串,是一种post原始请求,区别于form-data这种常用的key-value方式。
public static String result; public static void httpTest() throws ClientProtocolException, IOException { String token = "XRhjxAJZG3rFlPLg"; String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token; String json = "{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":234}}}"; HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); StringEntity postingString = new StringEntity(json);// json传递 post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); String content = EntityUtils.toString(response.getEntity()); // Log.i("test",content); System.out.println(content); result = content; }

以上代码中需要导入

import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;

Android中自带org.apache.http相关库文件,所以可以快捷键(ctrl+shift+o)一次导入成功。

热点内容
dota2linux 发布:2024-12-12 14:18:52 浏览:480
mysql数据库如何导入 发布:2024-12-12 14:11:14 浏览:920
监控器存储卡在哪里看 发布:2024-12-12 14:04:55 浏览:267
怎样把手机存储移到内存卡 发布:2024-12-12 13:49:31 浏览:673
如何知道服务器硬盘号码 发布:2024-12-12 13:49:28 浏览:496
安卓投屏怎么才能无延迟 发布:2024-12-12 13:40:52 浏览:854
androidl通知 发布:2024-12-12 13:22:59 浏览:532
如何搭建短信服务器 发布:2024-12-12 13:18:28 浏览:112
开拓者bose音响是哪个版本配置 发布:2024-12-12 13:01:27 浏览:571
泰拉瑞亚电脑联机服务器ip号 发布:2024-12-12 12:48:42 浏览:238