1. 程式人生 > >java通過java.net.URL傳送http請求呼叫.net寫的webService介面

java通過java.net.URL傳送http請求呼叫.net寫的webService介面

系統是用 java寫的,但需要呼叫同事用.net寫的一個webService介面。

所以記錄下java如何呼叫其他不同語言的介面的。

程式碼:

用到的工具類HttpUtil :

package cn.com.comit.appointment.modules.wechat.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http工具
 *
 */
public final class HttpUtil {
    /**
     * 模擬http協議傳送get請求
     **/
    public static String sendGetRequest(String url) {
        String result = "";
        InputStream in = null;
        
            HttpURLConnection connection=null;
            try{
                URL httpUrl = new URL(url);
                connection = (HttpURLConnection) httpUrl.openConnection();
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("Charset", "UTF-8");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                connection.setRequestMethod("GET");
                connection.connect();
                if (connection.getResponseCode() == 200) {
                    in = connection.getInputStream();
                    ByteArrayOutputStream bs=new ByteArrayOutputStream();
                    int n=0;
                    byte[] datas=new byte[2048];
                    while((n=in.read(datas))!=-1){
                        bs.write(datas, 0,n);
                    }
                    bs.flush();
                    result=new String(bs.toByteArray(),"utf-8");
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                try{
                    if (in != null){
                        in.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                try{connection.disconnect();}catch(Exception ex){}
            }
        return result;
    }/**
     * 模擬http協議傳送post請求
     **/
    public static String sendPostRequest(String url, String param) {
        InputStream in = null;
        String result = "";
        HttpURLConnection connection=null;
        try{
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.getOutputStream().write(param.getBytes("utf-8"));
            connection.getOutputStream().flush();
            if (connection.getResponseCode() == 200){
                in = connection.getInputStream();
                ByteArrayOutputStream bs=new ByteArrayOutputStream();
                int n=0;
                byte[] datas=new byte[2048];
                while((n=in.read(datas))!=-1){
                    bs.write(datas, 0,n);
                }
                bs.flush();
                result=new String(bs.toByteArray(),"utf-8");
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try{connection.disconnect();}catch(Exception ex){}
        }
        return result;
    }

    /**
     * 普通post檔案上傳
     */
    public static String upLoadAttachment(String url, File file){
        String result = null;
        
            HttpURLConnection connection=null;
            BufferedReader reader = null;
            try{
                URL httpUrl = new URL(url);
                connection = (HttpURLConnection) httpUrl.openConnection();
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("Charset", "UTF-8");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                String bound = "----------" + System.currentTimeMillis();
                connection.setRequestProperty("Content-Type","multipart/form-data; boundary="+bound);
                StringBuilder sb = new StringBuilder();
                sb.append("--");
                sb.append(bound);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName()+"\"\r\n");
                sb.append("Content-Type:application/octet-stream\r\n\r\n");
                byte[] head = sb.toString().getBytes("utf-8");
                OutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(head);
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                in.close();
                byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8");// 定義最後資料分隔線
                out.write(foot);
                out.flush();
                out.close();
                InputStream inn = connection.getInputStream();
                ByteArrayOutputStream bs=new ByteArrayOutputStream();
                int n=0;
                byte[] datas=new byte[2048];
                while((n=inn.read(datas))!=-1){
                    bs.write(datas, 0,n);
                }
                bs.flush();
                result=new String(bs.toByteArray(),"utf-8");
                return result;
            }catch(Exception ex){
                ex.printStackTrace();
            }finally {
                try{connection.disconnect();}catch(Exception ex){}
            }
        return null;
    }

}

用到的加密類DESEncryption :(因為同事那邊的介面需要加密和解密)

package cn.com.comit.appointment.modules.wechat.test.msg;

import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 加解密
 * @author admin
 *
 */
public class DESEncryption {

    //金鑰設定,可根據伺服器傳過來的金鑰設定。達到動態的效果。
    private String secret_key = "金鑰";
      
    //加密資料
    public static byte[] encrypt(String message, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(message.getBytes("UTF-8"));
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString();
    }
	
	//帶金鑰加密方法呼叫
    public  String DESEncrypt(String msg) {
        String encryt_data;
        String encryt_code;
        try {
            encryt_data = URLEncoder.encode(msg, "utf-8").toLowerCase();
            encryt_code = toHexString(encrypt(encryt_data, secret_key)).toUpperCase();
            return encryt_code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

實現類:因為返回的是json陣列格式資料:“【{“x”:"x"}】”;所以需要把其轉換為json物件

​
package cn.com.comit.appointment.modules.wechat.utils;

import java.util.Date;

import cn.com.comit.appointment.common.utils.DateUtils;
import cn.com.comit.appointment.modules.wechat.test.msg.DESEncryption;
import net.sf.json.JSONObject;

/**
 * 傳送查詢條件獲取資料
 * 
 *
 */
public class SendSearchUtil {
	
	public static void  main(String[] args){
		
		JSONObject  json=sendSearch("xx","xx","xx");
	}
	
	
	public static JSONObject sendSearch(String CaseType,String CarId,String TransgressTime){
		try {
		StringBuffer sb=new StringBuffer("{");
		sb.append("\"CaseType\":"+"\""+CaseType+"\"}_TE_");
		sb.append("{\"CarId\":"+"\""+CarId+"\"}_TE_");
		sb.append("{\"TransgressTime\":"+"\""+TransgressTime+"\"}_TE_");
		String key = DESEncryption.toHexString(DESEncryption.encrypt(DateUtils.formatDateTime(new Date()),"金鑰"));
			sb.append(key);
			System.out.println("sb---->"+sb.toString());
			//呼叫案件查詢介面,解析返回的json資料
			String url="介面地址/服務.svc/方法名";
			String params=sb.toString();
			String msg=HttpUtil.sendPostRequest(url,params);
			System.out.println("msg---->"+msg);
			 String s1=msg.replace("\\","");
		    String s2 =s1.replace("[","");
            String s3 =s2.replace("]", "");
			String json=s4.substring(1, s4.length()-1);
			 net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json);
			 System.out.println("jsonObject--->"+jsonObject.containsKey("CaseNumber"));
			 return jsonObject;
		} catch (Exception e) {
			System.out.println("e---"+e.getMessage());
			e.printStackTrace();
		}
		
		return null;
		
	}
	
}

​

最後成功獲取到資料!

我的座右銘:不會,我可以學;落後,我可以追趕;跌倒,我可以站起來;我一定行。

相關推薦

java通過java.net.URL傳送http請求呼叫.netwebService介面

系統是用 java寫的,但需要呼叫同事用.net寫的一個webService介面。 所以記錄下java如何呼叫其他不同語言的介面的。 程式碼: 用到的工具類HttpUtil : package cn.com.comit.appointment.modules.wech

java中使用Apache HttpClient傳送Http請求,並獲取返回結果

傳送http請求可以寫成一個工具類,HttpClient可以使用連線池建立,這樣的好處是我們可以自己定義一些配置,比如請求超時時間,最大連線數等等。 public class HttpUtil { private static CloseableHttpClient http

C#通過GET/POST方式傳送Http請求

介紹http請求的兩種方式,get和post方式。並用C#語言實現,如何請求url並獲取返回的資料 兩者的區別: 引數 Get請求把提交的資料進行簡單編碼,同時將url的一部分發送到伺服器 比如url:Http://127.0.0.1/login.j

java通過java.net.URL發送http請求調用接口

urn color val return http 功能 enc nts 實例 一般在*.html,*.jsp頁面中我們通過使用ajax調用接口,這個是我們通常用的。對於這些接口,大都是本公司寫的接口供自己調用,所以直接用ajax就可以。但是,如果是多家公司共同開發一個東西

Java工具類--通過HttpClient傳送http請求

在寫網路程式的時候,經常會有從網址獲取資料的需求,上一篇解析JSON就需要從百度獲取天氣資料,本文介紹一種Java傳送http請求的工具–HttpClient。 ##HttpClient的介紹 The most essential function of Ht

Java 傳送http請求

傳送GET方法的請求 /** * 向指定URL傳送GET方法的請求 * @param url 傳送請求的URL * @param param 請求引數,格式:name1=value1&name2=value2

java 常見幾種傳送http請求案例

<span style="font-family: Arial, Helvetica, sans-serif;">import java.io.BufferedReader;</span> import java.io.FileOutputS

Java傳送http請求(HttpClient)

public class HttpClientUtil { public static String doGet(String url, Map<String, String> param, String token) { // 建立Httpclient物件 Closeabl

java後端傳送http請求使用RestTemplate(簡單的都無敵了)

以前做專案,一聽到從後端傳送http請求,我就比較頭疼,因為要寫那麼一堆程式碼。 例如: String result= ""; BufferedReaderin = null; try { String urlNameS

【學習|總結】如何使用java和php傳送http請求

第一篇部落格寫什麼呢=w=看看下面的吧 最近在學php後臺開發,遇到一個學號驗證問題,所以需要攜帶token請求學校介面返回學生資訊,通過解析json來獲取學生學號。這讓我想起大一下學期做java音樂播放器時也涉及到了請求介面的問題,下面來看一下具體實現吧~

Java 傳送http請求demo

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.U

java 傳送http請求獲得json 以及解析json

博主在做一款圖書app的後臺,最近遇到的一個需求: 前端向後端返回圖書的isbn碼,後端向前端返回該isbn對應圖書的資訊,例如書名、作者、出版社、簡介等。 後端實現的邏輯: 讀取isbn碼,判斷是否為空,為空則報錯 檢視資料庫是否有與該isbn匹配的圖

Java傳送Http請求,解析html返回

宣告:本文系JavaEye網站釋出的原創部落格文章,未經作者書面許可,嚴禁任何網站轉載本文,否則必將追究法律責任! 今天是2008年7月7日星期一,下午一直在學校做個人開始頁面。因為離不開google的翻譯,所以想把google的翻譯整合到我的開始頁面中來,於是乎就遇到了一個

java 傳送http請求 返回字串 再進行解析(略)

package taobao.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamR

幾種方式的java傳送http請求的程式碼彙總

<span style="font-family: Arial, Helvetica, sans-serif;">import java.io.BufferedReader;</span>   import j

Java傳送Http請求工具類

package com.core.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Print

java傳送http請求的四種方式

自己對知識的總結 4種分別可傳送get和post請求的方法, 第1種:HttpURLConnection、 第2種:URLConnection、 第3種:HttpClient,,HttpClient常

JAVA傳送http請求呼叫http介面與方法

1.傳送POST請求,無引數名呼叫。 import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import

groovy如何使用java介面測試框架傳送http請求

本人在使用java寫框架做http介面測試的過程中,經過大神指點思路,發現用例還是要用指令碼語言來做會更加有利於後期的用例執行和用例管理。最近在研究大神推薦的groovy指令碼語言,略有一些小成績。下面分享一下如何在groovy裡面使用自己寫的基於java的介面測試框架來發送

Java 傳送http請求,上傳檔案

package wxapi.WxHelper; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.F