2015-08-26 230 views
0

因此,目前我試圖以XML文件的形式將一些數據導入到服務器。我已成功登錄並通過服務器的API來做所有事情。網站/服務器用XML響應,不確定是否相關。Android - 使用HttpURLConnection將XML文件發送到PHP API服務器

當我使用API​​的導入數據操作時,請求方法實際上是一個GET而不是POST,並且響應內容類型是text/xml。我想嚴格堅持使用HttpURLConnection,我知道發送這個XML文件將需要一些多部分內容類型的東西,但我不確定如何從這裏開始。 我看過這兩個例子,但它不適用於我的應用程序(至少不是直接)。另外,我真的不明白他們從哪裏得到了一些請求標題。

Send .txt file, document file to the server in android

http://alt236.blogspot.ca/2012/03/java-multipart-upload-code-android.html

從的開發者之一的消息都表示「要上傳的數據使用該動作= IMPORTDATA & gwID = NNNN和與通常的 多部分內容的編碼和將文件放置在請求正常。「

如何將我的XML文件通過其API發送到我的服務器?

回答

1

這是你如何做到這一點:

public void postToUrl(String payload, String address, String subAddress) throws Exception 
    { 
     try 
     { 
     URL url = new URL(address); 
     URLConnection uc = url.openConnection(); 
     HttpURLConnection conn = (HttpURLConnection) uc; 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-type", "text/xml");   
     PrintWriter pw = new PrintWriter(conn.getOutputStream()); 
     pw.write(payload); 
     pw.close(); 
     BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
     bis.close(); 

     } 
     catch (Exception e) 
     { 
     e.printStackTrace(); 
     } 
    } 
+0

它顯示了從Web瀏覽器訪問時成功導入甚至,我想那只是他們賺錢的方式。但是,當我訪問它時,實際網站仍然沒有變化。如果有幫助,其中一位開發人員說:「使用action = importData&gwID = nnnn並使用通常的Multipart內容編碼上傳數據,並像往常一樣將文件放在請求正文中」。我沒有經常與他們接觸。 – Marakalastic

0

這是我實現使用HttpURLConnection的一個多重表單數據上傳。

public class WebConnector { 
String boundary = "-------------" + System.currentTimeMillis(); 
private static final String LINE_FEED = "\r\n"; 
private static final String TWO_HYPHENS = "--"; 


private StringBuilder url; 
private String protocol; 
private HashMap<String, String> params; 
private JSONObject postData; 
private List<String> fileList; 
private int count = 0; 
private DataOutputStream dos; 

public WebConnector(StringBuilder url, String protocol, 
        HashMap<String, String> params, JSONObject postData) { 
    super(); 
    this.url = url; 
    this.protocol = protocol; 
    this.params = params; 
    this.postData = postData; 
    createServiceUrl(); 
} 

public WebConnector(StringBuilder url, String protocol, 
        HashMap<String, String> params, JSONObject postData, List<String> fileList) { 
    super(); 
    this.url = url; 
    this.protocol = protocol; 
    this.params = params; 
    this.postData = postData; 
    this.fileList = fileList; 
    createServiceUrl(); 
} 

public String connectToMULTIPART_POST_service(String postName) { 


    System.out.println(">>>>>>>>>url : " + url); 

    StringBuilder stringBuilder = new StringBuilder(); 

    String strResponse = ""; 
    InputStream inputStream = null; 
    HttpURLConnection urlConnection = null; 

    try { 
     urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection(); 
     urlConnection.setRequestProperty("Accept", "application/json"); 
     urlConnection.setRequestProperty("Connection", "close"); 
     urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible) "); 
     urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken()); 
     urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary); 

     urlConnection.setDoOutput(true); 
     urlConnection.setDoInput(true); 
     urlConnection.setUseCaches(false); 
     urlConnection.setChunkedStreamingMode(1024); 
     urlConnection.setRequestMethod("POST"); 
     dos = new DataOutputStream(urlConnection.getOutputStream()); 

     Iterator<String> keys = postData.keys(); 
     while (keys.hasNext()) { 
      try { 
       String id = String.valueOf(keys.next()); 
       addFormField(id, "" + postData.get(id)); 
       System.out.println(id + " : " + postData.get(id)); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
     try { 
      dos.writeBytes(LINE_FEED); 
      dos.flush(); 
      dos.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) { 
      for (int i = 0; i < fileList.size(); i++) { 

       File file = new File(fileList.get(i)); 
       if (file != null) ; 
       addFilePart("photos[" + i + "][image]", file); 
      } 
     } 
     // forming th java.net.URL object 

     build(); 
     urlConnection.connect(); 
     int statusCode = 0; 
     try { 
      urlConnection.connect(); 
      statusCode = urlConnection.getResponseCode(); 
     } catch (EOFException e1) { 
      if (count < 5) { 
       urlConnection.disconnect(); 
       count++; 
       String temp = connectToMULTIPART_POST_service(postName); 
       if (temp != null && !temp.equals("")) { 
        return temp; 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     // 200 represents HTTP OK 
     if (statusCode == HttpURLConnection.HTTP_OK) { 
      inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
      strResponse = readStream(inputStream); 
     } else { 
      System.out.println(urlConnection.getResponseMessage()); 
      inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
      strResponse = readStream(inputStream); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (null != inputStream) 
       inputStream.close(); 
     } catch (IOException e) { 
     } 
    } 
    return strResponse; 
} 

public void addFormField(String fieldName, String value) { 
    try { 
     dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED); 
     dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/); 
     /*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/ 
     dos.writeBytes(value + LINE_FEED); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

public void addFilePart(String fieldName, File uploadFile) { 
    try { 
     dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED); 
     dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED); 
     dos.writeBytes(LINE_FEED); 

     FileInputStream fStream = new FileInputStream(uploadFile); 
     int bufferSize = 1024; 
     byte[] buffer = new byte[bufferSize]; 
     int length = -1; 

     while ((length = fStream.read(buffer)) != -1) { 
      dos.write(buffer, 0, length); 
     } 
     dos.writeBytes(LINE_FEED); 
     dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED); 
    /* close streams */ 
     fStream.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void addHeaderField(String name, String value) { 
    try { 
     dos.writeBytes(name + ": " + value + LINE_FEED); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

public void build() { 
    try { 
     dos.writeBytes(LINE_FEED); 
     dos.flush(); 
     dos.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

private static String readStream(InputStream in) { 
    StringBuilder sb = new StringBuilder(); 
    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
     String nextLine = ""; 
     while ((nextLine = reader.readLine()) != null) { 
      sb.append(nextLine); 
     } 
    /* Close Stream */ 
     if (null != in) { 
      in.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return sb.toString(); 
} 

private void createServiceUrl() { 
    if (null == params) { 
     return; 
    } 
    final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator(); 
    boolean isParam = false; 
    while (it.hasNext()) { 
     final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next(); 
     url.append(mapEnt.getKey()); 
     url.append("="); 
     try { 
      url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8")); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
     url.append(WSConstants.AMPERSAND); 
     isParam = true; 
    } 
    if (isParam) { 
     url.deleteCharAt(url.length() - 1); 
    } 
} 

}

相關問題