2012-08-30 36 views
0

以下是從連接到網站並通過POST方法上載文件的Java客戶端中截取的內容。我必須在Visual Studio環境中重現此客戶端,但在Java環境中使用的setEntity()函數在.NET環境中沒有看到任何等效函數。將Web服務POST從Java轉換爲.NET

一切我已經找到點用這個...

public void uploadFile(File uploadFile, String partner, String key, 
      String baseUrl,boolean isPartner) throws IOException { 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(
     CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 
    ); 
    String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "=" 
      + partner.toUpperCase() + "&authKey=" 
      + key+ "&key=" 
      + key; 
    HttpPost httppost = new HttpPost(url); 
    MultipartEntity multipartEntity = new MultipartEntity(); 
    ContentBody contentBody = new FileBody(uploadFile, "text/xml"); 
    multipartEntity.addPart("dataFile", contentBody); 
    httppost.setEntity(multipartEntity); 

    HttpResponse response; 
    response = httpclient.execute(httppost); 

    HttpEntity resEntity = response.getEntity(); 

    if (resEntity != null) { 
     resEntity.consumeContent(); 
    } 

    httpclient.getConnectionManager().shutdown(); 
} 

的一切我已經在Visual Studio中使用這樣的事情下面的POST方法。 WebRequest對象沒有明顯的方式添加我需要的參數。

Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa") 
request.Method = "POST" 
Dim postData As String = StrData 
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) 
request.ContentType = "dataStr" 
request.ContentLength = byteArray.Length 
Dim dataStream As Stream = request.GetRequestStream() 
dataStream.Write(byteArray, 0, byteArray.Length) 
dataStream.Close() 
Dim response As WebResponse = request.GetResponse() 

任何指導將不勝感激。如果我的問題不清楚,請告訴我,我會再試一次。

+0

我的代碼看起來像Visual Basic。我不知道那種語言,但如果是這樣,你的標籤也應該反映這一點。 –

回答

0

可以添加下面的代碼段來添加參數

request.ContentType = 「應用程序/ x WWW的形式進行了urlencoded」

昏暗POSTDATA作爲字符串= 「NAME1 =」 + VALUE1 +」 & NAME2 =「+ VALUE2

昏暗的ByteArray作爲字節()= Encoding.UTF8.GetBytes(POSTDATA)

休息將保持相同。