Created
May 10, 2013 08:43
-
-
Save skyisle/5553239 to your computer and use it in GitHub Desktop.
crash reproduce with okhttp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.alanjeon.okhttptest; | |
import com.squareup.okhttp.OkHttpClient; | |
import android.app.Activity; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.View; | |
import java.io.BufferedInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
public class MyActivity extends Activity { | |
private static final String TAG = "MyActivity"; | |
/** | |
* Called when the activity is first created. | |
*/ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
AsyncTask.execute(new Runnable() { | |
@Override | |
public void run() { | |
testOkhttp(); | |
} | |
}); | |
} | |
}); | |
} | |
private void testOkhttp() { | |
try { | |
URL url = new URL("https://www.google.com/"); | |
OkHttpClient client = new OkHttpClient(); | |
HttpURLConnection okhttpConnection = client.open(url); | |
String body2 = get(okhttpConnection); | |
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); | |
String body = get(urlConnection); | |
if(body.equals(body2)) { | |
Log.d(TAG, "PASS!!"); | |
} else { | |
Log.d(TAG, "FAIL!! " + body.length() + " " + body2.length()); | |
} | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. | |
} catch (IOException e) { | |
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. | |
} | |
} | |
String get(HttpURLConnection connection) throws IOException { | |
InputStream in = null; | |
try { | |
// Read the response. | |
in = connection.getInputStream(); | |
byte[] response = readFully(in); | |
return new String(response, "UTF-8"); | |
} finally { | |
if (in != null) in.close(); | |
} | |
} | |
byte[] readFully(InputStream in) throws IOException { | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
byte[] buffer = new byte[1024]; | |
for (int count; (count = in.read(buffer)) != -1; ) { | |
out.write(buffer, 0, count); | |
} | |
return out.toByteArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment