I am trying to connect to a website where the site database adds a name to a list based on the url you connect with. I can't connect. The site works and I can access it in a browser. The error is an IOException.
if ((Boolean) value)
{
System.out.println("setValue");
try
{
URL myURL = new URL("http://app.bannervision.tv/api/add/" + data.name.get(row));
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e)
{
System.out.println("MalformedURLException");
// ...
}
catch (IOException e)
{
System.out.println("IOException");
System.out.println("http://app.bannervision.tv/api/add/" + data.name.get(row));
// openConnection() failed
// ...
}
}
Related
So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();
I was trying several days to get HTTPS connection right to connect to Yobit public API. I don't know what happen to my code. I have tried so many different examples but nothing works out on Yobit. Those codes and examples I have tried, they either give 411, 503 error or MalFormException:no protocol. Can anyone help me? I have very limited experience with HTTPS or web programming on Java. If any one can provide me solutions and references, I will really appreciate that.
public void buildHttpsConnection()
{
try {
URL url = new URL("https://yobit.net/api/3/info");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
System.out.println(con.getResponseCode());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try to use "https://www.yobit.net/api/3/info" URL Instead of "https://yobit.net/api/3/info"
It will give you the same result. You can validate it from the browser Window.
Check below snippet.
try {
URL url = null;
try {
url = new URL("https://www.yobit.net/api/3/info");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
try {
con.setRequestMethod("GET");
} catch (ProtocolException e1) {
e1.printStackTrace();
}
con.setRequestProperty("user-Agent", "Mozilla/5.0 (compatible; JAVA AWT)");
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
try {
System.out.println(con.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
Upon trying to connect to a host/server that does not exist, my program just seems to die. Stepping through with the debugger lends me nothing, it makes it to getResponseCode() and then just stops working. No exceptions are thrown from what I can tell and the program doesn't return.
Here is the relevant code snippet:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
When connecting to a valid URL, it works fine.
I fixed it, I needed to add http.setConnectTimeout(10000); after I opened the connection. Apparently whatever the default timeout was set as was so long that it appeared to never give a response at all, even when leaving the application open for several minutes.
class background_thread extends AsyncTask<String ,String , Boolean > {
protected Boolean doInBackground(String... params) {
String UR = "127.0.0.1/abc/index.php";
try {
URL url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
}
}
When I use the above code, in the HttpURLConnection the url turns red and Android Studio is showing an error can not resolve symbol url. What's wrong with the code?
I encountered the same problem. Just do:
import java.net.URL;
Put the line which is openning connection inside of try clause:
try {
URL url = new URL(UR);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
It is because the valiable url is a local one which is valid only inside the try clause.
Or declair the url outside of the try clause:
URL url;
try {
url = new URL(UR);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
With Java 7+, we can use the AutoClosable feature:
URL url;
try {
url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try (HttpURLConnection conn = (HttpURLConnection) url.openConnection())
// Do something...
} catch (IOException e) {
e.printStackTrace();
}
Sometimes you need a asimple 'gradlew clean'
"Click" on "Build"->"Clean Project" and that will perform a gradle clean
Or:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
Adding
import java.net.MalformedURLException;
solve the missing resolve symbol.
You must of course have this too:
import java.net.URL;
I have the following on a web servlet:
EDITED:
public String tryGoogleAuthentication(String auth_token){
HttpURLConnection connection = null;
try {
//connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2v1/tokeninfo?access_token={"+auth_token+"}")).openConnection();
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/user info")).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer {"+auth_token+"}");
connection.setRequestProperty("Host", "googleapis.com");
//read response
String response = fromInputStreamToString(connection.getInputStream());
System.out.println(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return CONST.STATUS_OK;
}
In android:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxxxxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
and
#Override
protected void onNewIntent(Intent intent) {
//super.onNewIntent(intent);
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
if(oauthToken != null){
authorizeGoogleSessionToServer(oauthToken);
}
}
After this, I send the request token to my servlet where I tried to get user profile, but with no success.
Could you please tell me what's wrong and why I'm getting error 400 from google?
Thanks.
Unfortunately, I can see a few issues with this already
you should never have curly braces in your URL or even in the Bearer header as stated in the draft.
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/userinfo?access_token={"+auth_token+"}")).openConnection()
400 means that you're missing something in your request, there is probably more information about it in the same response as specific error node.
Finally, take care, oauth_verifier param is from OAuth 1.
I suggest you test your request URL's, using the Google OAuth2 playground
Good luck!