Я столкнулся с подобной проблемой. Вот код, который поможет мне найти разрешение. Надеюсь, это вам поможет.
activity_main.xml
MainActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
// private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void sendGetRequest(View View) {
new GetClass(this).execute();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.end(client, viewAction);
// client.disconnect();
}
private class GetClass extends AsyncTask {
private final Context context;
public GetClass(Context c) {
this.context = c;
}
protected void onPreExecute() {
progress = new ProgressDialog(this.context);
progress.setMessage("Loading Get Method.....");
progress.show();
}
@Override
protected Void doInBackground(String... params) {
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09nks&apikey=DvlaSearchDemoAccount");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Выход на эмуляторе
HTH
Ссылки:
Используя imaps было большое предложение. Ни один из ответов, предоставленных просто, не работал на меня, таким образом, я погуглил еще немного и нашел что-то, что работало. Вот то, как мой код смотрит теперь.
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>@gmail.com", "<password>");
...
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
Это хорошо, потому что это вынимает избыточный Аутентификатор из изображения. Я рад, что это работало, потому что SSLNOTES.txt заставляет мою голову кружиться.
В JavaMail можно использовать imaps
в качестве схемы URL использовать IMAP по SSL. (См. SSLNOTES.txt
в Вашем распределении JavaMail для получения дополнительной информации.), Например, imaps://username%40gmail.com@imap.gmail.com/INBOX
.
Точно так же использование smtps
для отправки электронных писем через Gmail. например, smtps://username%40gmail.com@smtp.gmail.com/
. Снова, читайте SSLNOTES.txt
для получения дополнительной информации. Надежда это помогает!
Необходимо соединиться с Gmail с помощью SSL только. Установка следующих свойств вызовет это для Вас.
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false");
Если Вы хотели бы более пример кода при использовании JavaMail с Gmail (например, преобразование маркировок Gmail к именам папок IMAP или использования НЕАКТИВНОГО IMAP), действительно проверьте мою программу GmailAssistant на SourceForge.
Проверьте http://g4j.sourceforge.net/ . Существует созданное использование клиента минимального Gmail этого API.
URLName server = new URLName("imaps://<gmail-user-name>:<gmail-pass>@imap.gmail.com/INBOX");
Я использовал следующие свойства для получения магазина, и он работает хорошо.
"mail.imaps.host" : "imap.gmail.com"
"mail.store.protocol" : "imaps"
"mail.imaps.port" : "993"