2011-09-27 6 views
0

HTTP 연결을 만드는 가장 좋은 방법은? 나는 프록시 사용 등을 의미한다. 지금은이 일을 사용하고 있습니다 : 내 클라이언트 중 하나는 그가 바로 자신의 APN 설정에서 프록시를 설정 한 후 IllegalArgumentException를 가지고 나에게 알려주기 때문에안드로이드에서 HTTP 요청을하는 올바른 방법

StringBuilder entity = new StringBuilder(); 
entity.append("request body"); 

AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null); 

String proxyHost = android.net.Proxy.getDefaultHost(); 
int proxyPort = android.net.Proxy.getDefaultPort(); 
if (proxyHost != null && proxyPort > 0) { 
    HttpHost proxy = new HttpHost(proxyHost, proxyPort); 
    ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxy); 
} 
HttpPost httpPost = new HttpPost("https://w.qiwi.ru/term2/xmlutf.jsp"); 
httpPost.setEntity(new StringEntity(entity.toString(), "UTF-8")); 
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
HttpParams params = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(params, 15000); 
HttpConnectionParams.setSoTimeout(params, 30000); 
httpPost.setParams(params); 
HttpResponse httpResponse = httpClient.execute(httpPost); 

int responseCode = httpResponse.getStatusLine().getStatusCode(); 
if (responseCode == HttpStatus.SC_OK) { 
    // parsing response 
} 

I, 즉 괜찮은지 어떤지 정말 모르겠어요.

+0

@blackbelt 나는이 코드를 AsyncTask에서 사용합니다. – nixan

+0

@LalitPoptani 프록시를 사용하지 못했습니다. 안드로이드 전화에서 APN 설정에 프록시가 있으면 어떨까요? – nixan

+0

@nixan 그 점에 대해 미안 ... : ( –

답변

1

를 사용하여 호스트 API_REST_HOST의 실제 전화, 이런 식으로하게 executeRequest라는 하나의 방법 (플리커의 휴식 API에 대한 "api.flickr.com"와 같은 값이 될 수 있습니다 API_REST_HOST을.는 HTTP와 포트가 추가됩니다)

private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException { 
    HttpEntity entity = null; 
    HttpHost host = new HttpHost(API_REST_HOST, 80, "http"); 
    try { 
     final HttpResponse response = mClient.execute(host, get); 
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
      entity = response.getEntity(); 
      final InputStream in = entity.getContent(); 
      handler.handleResponse(in); 
     } 
    } catch (ConnectTimeoutException e) { 
     throw new ConnectTimeoutException(); 
    } catch (ClientProtocolException e) { 
     throw new ClientProtocolException(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     throw new IOException(); 
    } 
    finally { 
     if (entity != null) { 
      try { 
       entity.consumeContent(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

전화 이러한 방법으로 여기에서이 API는 :

final HttpGet get = new HttpGet(uri.build().toString()); 
    executeRequest(get, new ResponseHandler() { 
     public void handleResponse(InputStream in) throws IOException { 
      parseResponse(in, new ResponseParser() { 
       public void parseResponse(XmlPullParser parser) 
         throws XmlPullParserException, IOException { 
        parseToken(parser, token, userId); 
       } 
      }); 
     } 
    }); 

당신의 URI는 다음과 같이 구성되는 경우 :

final Uri.Builder builder = new Uri.Builder(); 
builder.path(ANY_PATH_AHEAD_OF_THE_BASE_URL_IF_REQD); 
builder.appendQueryParameter(PARAM_KEY, PARAM_VALUE); 
,

귀하의 mClient 클래스 수준 변수로이 방법

private HttpClient mClient; 

그리고 마지막으로 당신의 parseResponse이 방법으로 수행 할 수 있습니다를 선언 (XML 데이터를 구문 분석하고 싶은 말은)

private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException { 
    final XmlPullParser parser = Xml.newPullParser(); 
    try { 
     parser.setInput(new InputStreamReader(in)); 

     int type; 
     while ((type = parser.next()) != XmlPullParser.START_TAG && 
       type != XmlPullParser.END_DOCUMENT) { 
      // Empty 
     } 

     if (type != XmlPullParser.START_TAG) { 
      throw new InflateException(parser.getPositionDescription() 
        + ": No start tag found!"); 
     } 

     String name = parser.getName(); 
     if (RESPONSE_TAG_RSP.equals(name)) { 
      final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT); 
      if (!RESPONSE_STATUS_OK.equals(value)) { 
       throw new IOException("Wrong status: " + value); 
      } 
     } 

     responseParser.parseResponse(parser); 

    } catch (XmlPullParserException e) { 
     final IOException ioe = new IOException("Could not parse the response"); 
     ioe.initCause(e); 
     throw ioe; 
    } 
} 

이 코드는 처리한다 모든 가능한 예외에 대해 설명하고 HTTP 연결에서 입력 스트림에서 오는 응답을 올바르게 구문 분석하는 방법을 보여줍니다.

이미 알고 계시 겠지만 UI 스레드가 아닌 별도의 스레드에서 사용해야합니다. That 's it :)

+0

고마워. – nixan

관련 문제