2012-12-04 220 views
9

我开发了一个HTTP GET方法,可以清楚地工作。Android - HTTP GET请求

public class GetMethodEx { 


public String getInternetData() throws Exception{ 

     new TrustAllManager(); 
     new TrustAllSSLSocketFactory(); 

     BufferedReader in = null; 
     String data = null; 


     try 
     { 
      HttpClient client = new DefaultHttpClient(); 
      URI website = new URI("https://server.com:8443/Timesheets/ping"); 
      HttpGet request = new HttpGet(); 
      request.setURI(website); 
      HttpResponse response = client.execute(request); 
      response.getStatusLine().getStatusCode(); 

      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String l = ""; 
      String nl = System.getProperty("line.separator"); 
      while ((l = in.readLine()) !=null){ 
       sb.append(l + nl); 
      } 
      in.close(); 
      data = sb.toString(); 
      return data;   
     } finally{ 
      if (in != null){ 
       try{ 
        in.close(); 
        return data; 
       }catch (Exception e){ 
        e.printStackTrace(); 
       } 
      } 
     } 
} 

这是我的模拟器的打印屏幕中检索从www.google.com

SCREEN SHOT OF GOOGLE.COM WORKING

以下代码是我的检索方法,以将其显示在屏幕上的响应时。

public class Home extends Activity { 

TextView httpStuff; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.httpexample); 
    httpStuff = (TextView) findViewById(R.id.tvhttp); 
    new LongOperation().execute(""); 

} 

private class LongOperation extends AsyncTask<String, Void, String> { 
    @Override 

    protected String doInBackground(String... params) { 

     GetMethodEx test = new GetMethodEx();  
     String returned = null; 

    try { 
     returned = test.getInternetData(); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
     return returned; 
    }  

    @Override 
    protected void onPostExecute(String result) {  
    httpStuff.setText(result);  
    } 

但是,当我尝试用我自己的服务器。

https://server:port/xwtimesheets/ping

我有以下的屏幕

MY SERVER, NOT WORKING

回答

8

这是您的GetMethodEx类的编辑版本。 MySSLSocketFactory允许您连接任何服务器而不检查其证书。如你所知,这是不安全的。我建议您将您的服务器证书作为可信的添加到您的设备中。

顺便说一句,您的服务器证书的有效期已过期。即使您将其添加为可信,您也可能无法连接到您的服务器。

public class GetMethodEx { 

public String getInternetData() throws Exception { 


    BufferedReader in = null; 
    String data = null; 

    try { 
     HttpClient client = new DefaultHttpClient(); 
     client.getConnectionManager().getSchemeRegistry().register(getMockedScheme()); 

     URI website = new URI("https://server.com:8443/XoW"); 
     HttpGet request = new HttpGet(); 
     request.setURI(website); 
     HttpResponse response = client.execute(request); 
     response.getStatusLine().getStatusCode(); 

     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String l = ""; 
     String nl = System.getProperty("line.separator"); 
     while ((l = in.readLine()) != null) { 
      sb.append(l + nl); 
     } 
     in.close(); 
     data = sb.toString(); 
     return data; 
    } finally { 
     if (in != null) { 
      try { 
       in.close(); 
       return data; 
      } catch (Exception e) { 
       Log.e("GetMethodEx", e.getMessage()); 
      } 
     } 
    } 
} 

public Scheme getMockedScheme() throws Exception { 
    MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory(); 
    return new Scheme("https", mySSLSocketFactory, 443); 
} 

class MySSLSocketFactory extends SSLSocketFactory { 
    javax.net.ssl.SSLSocketFactory socketFactory = null; 

    public MySSLSocketFactory(KeyStore truststore) throws Exception { 
     super(truststore); 
     socketFactory = getSSLSocketFactory(); 
    } 

    public MySSLSocketFactory() throws Exception { 
     this(null); 
    } 

    @Override 
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, 
      UnknownHostException { 
     return socketFactory.createSocket(socket, host, port, autoClose); 
    } 

    @Override 
    public Socket createSocket() throws IOException { 
     return socketFactory.createSocket(); 
    } 

    javax.net.ssl.SSLSocketFactory getSSLSocketFactory() throws Exception { 
     SSLContext sslContext = SSLContext.getInstance("TLS"); 

     TrustManager tm = new X509TrustManager() { 
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
      public X509Certificate[] getAcceptedIssuers() { 
       return null; 
      } 
     }; 
     sslContext.init(null, new TrustManager[] { tm }, null); 
     return sslContext.getSocketFactory(); 
    } 
} 
} 
+0

非常感谢您的先生。 –

+0

@Akdeniz嗨!,我尝试了你的推荐,但是我收到了一些错误,我发布了一个问题。你能否告诉我我做错了什么? http://stackoverflow.com/questions/23900054/android-php-sending-a-get-request-to-php-server 谢谢 –

5

您这里有一个错误:

URI website = new URI("https://https://ts.xoomworks.com:8443/XoomworksTimesheets/ping"); 

您正在使用 “https://开头” 两次。

编辑: 我得到的代码here

您的代码应该是这样的:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; 

DefaultHttpClient client = new DefaultHttpClient(); 

SchemeRegistry registry = new SchemeRegistry(); 
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); 
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); 
registry.register(new Scheme("https", socketFactory, 8443)); 
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry); 
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); 

// Set verifier  
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); 

// Example send http request 
final String url = "https://ts.xoomworks.com:8443/XoomworksTimesheets/ping/"; 
HttpPost httpPost = new HttpPost(url); 
HttpResponse response = httpClient.execute(httpPost); 

response.getStatusLine().getStatusCode(); 

in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
StringBuffer sb = new StringBuffer(""); 
String l = ""; 
String nl = System.getProperty("line.separator"); 
while ((l = in.readLine()) !=null){ 
    sb.append(l + nl); 
} 
in.close(); 
data = sb.toString(); 
return data; 

我没有测试它在我的结束,但它应该工作。注意你使用的是端口8433而不是433,所以我在socketfactory方案中改变了它。

+1

对不起,编辑和修复。仍然是同样的问题。 –

+0

当你做google.com请求时,你做到了没有https的权利?你有没有尝试这样做到你的服务器没有SSL连接? –

+0

我也试过Facebook并使用https协议。没有SSL连接,我的服务器无法工作。我有一个允许所有未签名证书的类,我知道这是不安全的。但我不确定如何在我的代码中实现此类。 –

2

保重,与API新版本的所有代码已被弃用

下面是一个http获取新示例api的示例。从Android的网站

RequestQueue queue = Volley.newRequestQueue(this); 
String url ="http://www.google.com"; 

// Request a string response from the provided URL. 
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
    @Override 
    public void onResponse(String response) { 
     // Display the first 500 characters of the response string. 
     mTextView.setText("Response is: "+ response.substring(0,500)); 
    } 
}, new Response.ErrorListener() { 
    @Override 
    public void onErrorResponse(VolleyError error) { 
     mTextView.setText("That didn't work!"); 
    } 
}); 
// Add the request to the RequestQueue. 
queue.add(stringRequest); 

来源:https://developer.android.com/training/volley/simple.html

1

HttpClient已被弃用。因此,新的方法来做到: 首先,在加的build.gradle的两个依赖:

compile 'org.apache.httpcomponents:httpcore:4.4.1' 
compile 'org.apache.httpcomponents:httpclient:4.5' 

然后在doBackground方法写在ASyncTask这个代码。

URL url = new URL("http://localhost:8080/web/get?key=value"); 
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); 
urlConnection.setRequestMethod("GET"); 
int statusCode = urlConnection.getResponseCode(); 
if (statusCode == 200) { 
     InputStream it = new BufferedInputStream(urlConnection.getInputStream()); 
     InputStreamReader read = new InputStreamReader(it); 
     BufferedReader buff = new BufferedReader(read); 
     StringBuilder dta = new StringBuilder(); 
     String chunks ; 
     while((chunks = buff.readLine()) != null) 
     { 
     dta.append(chunks); 
     } 
} 
else 
{ 
    //Handle else 
} 

注意不要忘记处理代码中的例外。