2014-04-22 4 views
0

나는 triyng이므로 서버에 POST 요청을 보냅니다. 다음 Java 코드는 PC 응용 프로그램에서 작동하지만 Android 응용 프로그램에서는 작동하지 않습니다. Iternet 사용 권한이 추가되었으므로이 게시물을 보내려면 어떻게해야합니까? Android 용으로이 코드를 바꾸려면 다른 방법과 라이브러리를 사용해야합니까?Android 응용 프로그램에서 POST 보내기

 String hostname = "xxxxxxx.box"; 
     int port = 80; 
     InetAddress addr = InetAddress.getByName(hostname); 
     Socket sock = new Socket(addr, port); 
     String SID = new classSID("xxxxxx").obtainSID(); 
     BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8")); 
     String str = "enabled=on&username="+givenName+"&email="+givenEmail+"&password="+givenPassword+"&frominternet=on&box_admin_rights=on&phone_rights=on&homeauto_rights=on&uid=&sid="+SID+"&apply="; 

     //////////////////////////////////////////////////////////////////////////////////////////// 
     wr.write("POST /system/boxuser_edit.lua HTTP/1.1"); 
     wr.write("Host: xxxxxx:80" + "\r\n"); 
     wr.write("Accept: text/html" + "\r\n"); 
     wr.write("Keep-Alive: 300" + "\r\n"); 
     wr.write("Connection: Keep-Alive" + "\r\n"); 
     wr.write("Content-Type: application/x-www-form-urlencoded"+"\r\n"); 
     wr.write("Content-Length: "+str.length()+"\r\n"); 
     wr.write("\r\n"); 
     wr.write(str+"\r\n"); 
     wr.flush(); 
    ////////////////////////////////////////////////////////////////////////////////////////////   
     BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(),"UTF-8")); 
     String line; 
     while((line = rd.readLine()) != null) 
      Log.v("Response", line);  

     wr.close(); 
     rd.close(); 
     sock.close(); 
} 
+0

무엇이 오류인가 –

+0

안녕하세요, 오류를 잡으려고했지만 오류가 없습니다. 그냥 작동하지 않습니다. – Soyer

+0

호스트 이름 대신 ip를 사용하고 아래 제공된 코드 –

답변

1

이 시도 : 당신의 안드로이드 장치가 NTO

private static final String  UTF_8  = "UTF-8"; 
/** 
* @param hostNameOrIP 
*   : the host name or IP<br/> 
* @param webService 
*   : the web service name<br/> 
* @param classOrEndPoint 
*   : the file or end point<br/> 
* @param method 
*   : the method being called<br/> 
* @param parameters 
*   : the parameters to be sent in the message body 
* @return 
*/ 
public static String connectPOST(final String url, final HashMap<String, String> parameters) { 
    final StringBuilder postDataBuilder = new StringBuilder(); 
    if (null != parameters) { 
     for (final HashMap.Entry<String, String> entry : parameters.entrySet()) { 
      if (postDataBuilder.length() != 0) { 
       postDataBuilder.append("&"); 
      } 
      postDataBuilder.append(entry.getKey()).append("=").append(entry.getValue()); 
     } 
    } 

    final StringBuffer text = new StringBuffer(); 
    HttpURLConnection conn = null; 
    OutputStream out = null; 
    InputStreamReader in = null; 
    BufferedReader buff = null; 
    try { 
     final URL page = new URL(url); 
     conn = (HttpURLConnection) page.openConnection(); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     conn.setUseCaches(false); 
     conn.setRequestMethod("POST"); 
     out = conn.getOutputStream(); 
     final byte[] postData = postDataBuilder.toString().getBytes(UTF_8); 
     out.write(postData); 
     out.flush(); 
     out.close(); 
     final int responseCode = conn.getResponseCode(); 
     if ((responseCode == 401) || (responseCode == 403)) { 
      // Authorization Error 
      Log.e(TAG, "Authorization error in " + url + "(" + postDataBuilder.toString() + ")"); 
      // throw new Exception("Authorization Error in " + method + "(" 
      // + postDataBuilder.toString() + ")"); 
      return null; 
     } 
     if (responseCode == 404) { 
      // Authorization Error 
      Log.e(TAG, "Not found error in " + url + "(" + postDataBuilder.toString() + ")"); 
      // throw new Exception("Authorization Error in " + method + "(" 
      // + postDataBuilder.toString() + ")"); 
      return null; 
     } 

     if ((responseCode >= 500) && (responseCode <= 504)) { 
      // Server Error 
      Log.e(TAG, "Internal server error in " + url + "(" + postDataBuilder.toString() + ")"); 
      // throw new Exception("Internal Server Error in " + method + 
      // "(" 
      // + postDataBuilder.toString() + ")"); 
      return null; 
     } 
     in = new InputStreamReader((InputStream) conn.getContent()); 
     buff = new BufferedReader(in); 
     String line; 
     while ((null != (line = buff.readLine())) && !"null".equals(line)) { 
      text.append(line + "\n"); 
     } 
     buff.close(); 
     buff = null; 
     in.close(); 
     in = null; 
     conn.disconnect(); 
     conn = null; 
    } catch (final Exception e) { 
     Log.e(TAG, "Exception while connecting to " + url + " with parameters: " + postDataBuilder + ", exception: " + e.toString() + ", cause: " 
       + e.getCause() + ", message: " + e.getMessage()); 
     e.printStackTrace(); 
     return null; 
    } finally { 
     if (null != out) { 
      try { 
       out.close(); 
      } catch (final IOException e1) { 
      } 
      out = null; 
     } 
     if (null != buff) { 
      try { 
       buff.close(); 
      } catch (final IOException e1) { 
      } 
      buff = null; 
     } 
     if (null != in) { 
      try { 
       in.close(); 
      } catch (final IOException e1) { 
      } 
      in = null; 
     } 
     if (null != conn) { 
      conn.disconnect(); 
      conn = null; 
     } 
    } 
    final String temp = text.toString(); 
    if (text.length() > 0) { 
     Log.i(TAG, "Success in " + url + "(" + postDataBuilder.toString() + ") = " + temp); 
     return temp; 
    } 
    Log.w(TAG, "Warning: " + url + "(" + postDataBuilder.toString() + "), text = " + temp); 
    return null; 
} 
+0

p.S.로 테스트하십시오. 포트 80에 대한 포트를 지정하지 않아도됩니다. –

+0

Hello Shereef, Communication 클래스의 출처와 왜 (InputStream) 오류가 발생했는지 알려주실 수 있습니까? 정말 고마워! – Soyer

+0

죄송합니다. 통신 클래스가 내 클래스입니다. 모든 참조가 제거되었습니다. –

1

문제는 포트 당신이 필요로하는 80에 소켓을 만드는 것입니다 로컬 호스트 이름을 해석 할 수 있기 때문에 대신 호스트 이름의 IP를 사용하는 것을 고려 안드로이드에있는 포트 < 1024에 액세스 할 수있는 루트 권한. issue