http接口开发及调用

时间:2025-03-23 10:42:32

一般用http的post,尽量不用get;

开发中一般都使用的jar包,比较成熟,方便,易用;当然了,直接用java提供的也行

package ;

import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/*
 * Http接口 post
 * 接收下属客户端上传样本,保存样本文件
 * apache官网可以下载最新的jar包和demo
 * /
 */
public class TestSampleUpload4client {
public static void main(String[] args) throws ClientProtocolException, IOException{
String url = "http://192.168.1.6:8010/xxxxxxxxxxx/sample/";
// 配置要 POST 的数据  
MultipartEntityBuilder multipartEntityBuilder = ();
// 设置为浏览器兼容模式   
(HttpMultipartMode.BROWSER_COMPATIBLE);  
// 设置请求的编码格式
((HTTP.UTF_8));
ContentType TEXT_PLAIN = ("text/plain", (HTTP.UTF_8)); 

//设置一致的编码格式极其重要,否则容易出现乱码,不管客户端是以什么语言什么方式进行调用,必须让其编码格式与接收端一致;
("userName", "admin",TEXT_PLAIN);
("psd", "admin",TEXT_PLAIN);
("mac", "ma2343344f1333",TEXT_PLAIN);
("md5", "afy67juu8776a",TEXT_PLAIN);
("type", "sample",TEXT_PLAIN);
//文件路径
File file = new File("D:\\glpt\\");
("file", file);

/*
* 以下的参数提交方式也行
StringBody userName = new StringBody("admin", (
                "text/plain", Consts.UTF_8));
StringBody password = new StringBody("admin", (
                "text/plain", Consts.UTF_8));
// 把文件转换成流对象FileBody
FileBody bin = new FileBody(file);
("username", userName);
("password", password);
("file", bin);
*/
post(url,multipartEntityBuilder);
}

public static void post(String url,MultipartEntityBuilder multipartEntityBuilder) throws ClientProtocolException, IOException{
// 建立HttpPost对象 
HttpPost httppost = new HttpPost(url);
HttpClient httpclient = ().build();
// 生成 HTTP POST 实体
HttpEntity httpEntity = ();
(httpEntity);
// 发送Post,并返回一个HttpResponse对象
HttpResponse httpResponse = (httppost);
// 以下两行可以得到指定的Header
// Header header = ("Content-Length");
// String headerVal = ();
HttpEntity httpEntity2 = ();
("().getStatusCode():"+().getStatusCode());
// 如果状态码为200,就是正常返回
if (().getStatusCode() == HttpStatus.SC_OK) {
String result = (httpEntity2);
// 得到返回的字符串
(result);
// 如果是下载文件,可以用().getContent()返回InputStream
}else if (().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
// 如果状态码为302
String locationUrl = ("location").getValue();
post(locationUrl,multipartEntityBuilder);
}else {
String result = (httpEntity2);
// 得到返回的字符串
(result);
}
}

}









/**

*另一种处理方式
* @param args
* @throws UnsupportedEncodingException
* @throws IOException 
* @throws ClientProtocolException 
 
public static void main(String[] args) throws ClientProtocolException, IOException{
// TODO Auto-generated method stub
// POST的URL
String url = "http://192.168.10.203:8010/manageplatform/sample/";
// 建立HttpPost对象 
HttpPost httppost = new HttpPost(url);
// 建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();

// 添加参数
(new BasicNameValuePair("userName", "admin"));
(new BasicNameValuePair("psd", "admin"));
(new BasicNameValuePair("mac", "mac3333333333"));
(new BasicNameValuePair("md5", "md5555555555"));
(new BasicNameValuePair("type", "sample"));



HttpClient httpclient = new DefaultHttpClient();
// 设置编码
(new UrlEncodedFormEntity(params, HTTP.UTF_8));

// 发送Post,并返回一个HttpResponse对象
HttpResponse httpResponse = (httppost);
// 以下两行可以得到指定的Header
Header header = ("Content-Length");
String headerVal = ();


HttpEntity httpEntity = ();


if (().getStatusCode() == HttpStatus.SC_OK) {// 如果状态码为200,就是正常返回
String result = (httpEntity);
// 得到返回的字符串
(result);
// 打印输出
// 如果是下载文件,可以用().getContent()返回InputStream
}else {
String result = (httpEntity);
// 得到返回的字符串
(result);
}
}
*/

}


以上例子中http请求了一个url:http://192.168.:8010/xxxxxxxx/sample/

其中是用struts配置的;对应的action方法如下:

/**
* HTTP接口,
* 接收下属客户端及子管理中心上传样本,保存样本文件

* @return
*/
public void sampleUpload() {
OutputStream out = null;
try {
out = ();
String result = "Response=101;";
String path = ().getServletContext().getRealPath("/");
(path);
//用户认证
String userName = ("userName");
String psd = ("psd");
//此处省略了用户权限认证的操作;
String md5 = ("md5");
String mac = ("mac");
String type = ("type");
String ip = ();

if ((md5) || (mac) || (type)) {
result = "Response=011;";
} else {
for (int i = 0; i < (); i++) {
try {
String filename = (i);
String savePath = ((type)) ? path + "WEB-INF/uploadPath/" + type : (type);
if (!new File(savePath).exists()) {
new File(savePath).mkdirs();
}


filename = savePath + "/" + filename;
// sampleName = (i);
FileOutputStream fos = new FileOutputStream(filename);
InputStream is = new FileInputStream((i));
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = (buffer)) > 0) {
(buffer, 0, count);
}
();
();
filename = ('\\', '/');
result = "Response=000;";

result = (type, md5, mac, filename, ip);
} catch (Exception e) {
result = "Response=101;";
();
}
}
}
//记录接口日志
("1", mac, md5, ip, result);
//返回操作结果
(());
();
} catch (IOException e1) {
();
} finally {
try {
if (out != null)
();
} catch (IOException e) {
();
}
}





}