http请求接口公共方法。(restful方式)

来源:互联网 发布:美国物价知乎 编辑:程序博客网 时间:2024/05/29 19:41

 调用接口的公共方法。

package com.info.web.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.junit.Test;




/**
 * 
 * @author Administrator 公共调用接口
 *
 */
public class CommCallInterface {
private static Logger logger = Logger.getLogger(CommCallInterface.class); 
public static CommCallInterface commCallInterface;

public static CommCallInterface getInstance() {
if (commCallInterface == null) {
commCallInterface = new CommCallInterface();
}
return commCallInterface;
}


public static String commHttp(String reqPath, String param, String method) {
URL url;
String result = "";
logger.info("===========接口信息============");
logger.info("reqPath==========="+reqPath);
logger.info("param==========="+param);
logger.info("method==========="+method);
try {

url = new URL(reqPath);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod(method);
http.setRequestProperty("Content-Type", "application/json");
http.setDoInput(true);
http.setDoOutput(true);
/*
* System.setProperty("sun.net.client.defaultConnectTimeout",
* "30000");// 连接超时30秒
* System.setProperty("sun.net.client.defaultReadTimeout", "30000");
* // 读取超时30秒
*/
http.setConnectTimeout(150000000);// 连接超时 单位毫秒
http.setReadTimeout(1500000000);// 读取超时 单位毫秒
http.connect();
if (null != param) {
OutputStream os = http.getOutputStream();
os.write(param.getBytes("UTF-8"));// 传入参数  
os.flush(); 
os.close();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream(),"UTF-8"));

            String line;  
            while ((line = bufferedReader.readLine()) != null) {  
                result +=  line ;  
            }
            logger.info("result==========="+result);
} catch (MalformedURLException e) {
e.printStackTrace();
logger.info("result(MalformedURLException)==========="+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.info("result(IOException)==========="+e.getMessage());
}catch (Exception e) {
e.printStackTrace();
logger.info("result(Exception)==========="+e.getMessage());
}
return result;
}




/**
* 模拟http请求,上传文件
* 下午5:12:01
* huan
* @param url
* @param file
* @return
*/
public static String upload( String url , File file ){
        //接受反回的Json  
        String boty="";
        //实例化defaultHttpClient  
        DefaultHttpClient hc=new DefaultHttpClient();  
        try {  
            //实例化post方式访问并且把路径放入  
            HttpPost httppost=new HttpPost(url);  
            //把需要的参数传入  
          
            FileBody fileBody = new FileBody(file);  
            MultipartEntity entity = new MultipartEntity();  
            entity.addPart("file", fileBody); 
            httppost.setEntity(entity); 
            //执行访问返回resp  
            HttpResponse resp=hc.execute(httppost);  
            //获取访问的结果  
            HttpEntity httpentity=resp.getEntity();  
            //把返回的结果转成字符串  
            boty=EntityUtils.toString(httpentity);  
              
        } catch (Exception e) {  
            // TODO: handle exception  
            e.printStackTrace();  
        }//运行完后执行  
        finally {  
            hc.getConnectionManager().shutdown();  
        }
        return boty;
}


/**
* 固定取url
* 下午5:54:23
* huan
* @param boty
* @return
*/
/*public static String uploadUrl(String boty){
String url = "";
JSONObject jsonObject =JSONObject.fromObject(boty);
if(jsonObject.get("status").equals(0)){
JSONArray jsonArray= (JSONArray) jsonObject.get("results");
url= (String) jsonArray.getJSONObject(0).get("Url");
}
return url;
}*/




@Test
public void test(){
//请求的url
String url ="####";
//post请求传入的参数
String param = "";
//提交方式
String method = "POST";
//调用请求
String rest = CommCallInterface.getInstance().commHttp(url, param, "POST");
}
}