如何使用Java发送GET请求
我想在我的Android应用程序中发送GET请求,编写了下面的代码,但是当我使用调试器进行检查时,它给出了某种SSL错误。 由于是用来登录我的代码通过HTTP GET如何使用Java发送GET请求
private class AsyncLogin extends AsyncTask<String, String, String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
HttpsURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
return "exception";
}
try {
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Origin","https://myserver.com");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpsURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return(result.toString());
}else{
return("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(LoginActivity.this,SuccessActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}else if (result.equalsIgnoreCase("false")){
Toast.makeText(getApplicationContext(), "Invalid email or password", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
Toast.makeText(LoginActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
我的应用结束了这一次函数被调用。
org.apache.harmony.security.fortress.Engine.getInstance
你为什么投给HttpsURLConnection
,正常HttpURLConnection
应该做的,也是与HTTP和HTTPS的作品。 接下来我会用Log.e(TAG, "error creating HTTP connection", e);
代替e.printStackTrace();
,然后你会看到会发生什么。 你可以在这里发布Stacktrace吗?然后我们可以看到它是什么错误。
BTW: conn.setDoInput(true); conn.setDoOutput(true);
是没有必要的简单GET请求。
这是错误粘贴让我编辑我不是铸造它 –
有没有在日志stacktrace –
引起:java.lang.ClassCastException:com.android.okhttp.internal.http.HttpURLConnectionImpl不能转换为javax.net .ssl.HttpsURLConnection –
也许你可以告诉我们什么样的错误。 – stdunbar
@stdunbar没有错误记录只会杀死我的应用程序进程。 –
添加一些'Log.d(TAG,“您的消息..”);'怀疑代码,以便您可以找到代码仍然可用的位置。 –