2011-09-27 84 views
0

这是进行HTTP连接的最佳方式。我的意思是使用代理等。现在我用这一个:在Android中进行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 
} 

我真的不知道,如果这是确定的,因为我的一个客户告诉我,他有一个IllegalArgumentException在他的APN设置设置代理之后。

+0

@blackbelt我在AsyncTask中使用此代码 – nixan

+0

@LalitPoptani我还没有发现任何代理的使用。如果在你的android手机中会有APN设置中的代理呢? – nixan

+0

@nixan对不起,不知道那个...... :( –

回答

1

使用名为executeRequest一个方法,这使得该主机API_REST_HOST的实际调用,这样(API_REST_HOST可以是Flickr的REST API,如“api.flickr.com”的数值,这个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); 

您的移动客户端被声明为一个类级别的变量这样

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线程中。 就是这样:)

+0

谢谢,我会试试。 – nixan