简体   繁体   English

Android - HTTP GET 请求

[英]Android - HTTP GET Request

I have developed a HTTP GET Method that clearly works.我开发了一个明显有效的 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();
                }
            }
        }
}

Here is a print screen of my emulator when retrieving a response from www.google.com这是从 www.google.com 检索响应时我的模拟器的打印屏幕

SCREEN SHOT OF GOOGLE.COM WORKING GOOGLE.COM 工作的屏幕截图

The following code is my retrieval method to display it on screen.以下代码是我在屏幕上显示它的检索方法。

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);       
  }

However, when I try it with my own server.但是,当我用自己的服务器尝试时。

" https://server:port/xwtimesheets/ping " " https://server:port/xwtimesheets/ping "

I have the following screen我有以下屏幕

MY SERVER, NOT WORKING 我的服务器,不工作

Here is edited version of your GetMethodEx class.这是您的 GetMethodEx 类的编辑版本。 MySSLSocketFactory allows you to connect any server without checking their certificate. MySSLSocketFactory 允许您连接任何服务器而无需检查其证书。 As you know it, this is not safe.如您所知,这并不安全。 I recommend you to add your servers' certificate as trusted to your device.我建议您将服务器的证书添加到您的设备中。

By the way your servers certificate validity date is expired.顺便说一下,您的服务器证书有效期已过期。 Even if you add it as trusted, you may not connect to your server.即使您将其添加为受信任,您也可能无法连接到您的服务器。

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();
    }
}
}

You have an error here:你在这里有一个错误:

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

You are using "https://" twice.您使用了两次“https://”。

EDIT: I got the code from here编辑:我从这里得到了代码

Your code should look like:您的代码应如下所示:

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;

I did not test it on my end, but it should work.我没有对它进行测试,但它应该可以工作。 Note you are using the port 8433 instead of 433, so I changed it in the socketfactory scheme.请注意,您使用的是端口 8433 而不是 433,因此我在 socketfactory 方案中更改了它。

Take care, with the new version of API all this code is deprecated !请注意,新版本的 API 已弃用所有这些代码

Here is an example of http get with the new api .这是使用新 api 的 http get 示例

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);

Source from android website : https://developer.android.com/training/volley/simple.html来自android网站的来源: https : //developer.android.com/training/volley/simple.html

HttpClient is deprecated.不推荐使用HttpClient So new way to do: First, add the two dependencies in build.gradle:所以新方法:首先,在 build.gradle 中添加两个依赖项:

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

Then write this code in ASyncTask in doBackground method.然后在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
 }

Note : Don't forget to handle the Exceptions in code .注意不要忘记处理代码中的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM