Calling an API that have username and password in Java - java

I'm trying to connect to an API that has a username and password with this code:
try {
URL url = new URL("https://url?UserName=username&Password=password");
Connection = (HttpURLConnection) url.openConnection();
//Request setup
Connection.setRequestMethod("GET");
Connection.setConnectTimeout(5000);
Connection.setReadTimeout(5000);
int status = Connection.getResponseCode();
System.out.println(status);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
But I get the error:
java.net.SocketException: Connection reset
I kept searching and I found another format for the URL which is:
URL url = new URL("Https:username:password#url);
When I tried, it gave me the error:
java.net.MalformedURLException: For input string:password#url
I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work.
The password has words, numbers, and a special character!
What am I doing wrong?

Try to encode your URL, this way:
HttpURLConnection connection = (HttpURLConnection)
new URL("https://url?UserName" +
URLEncoder.encode(username, "UTF-8") +
"&Password=" +
URLEncoder.encode(password, "UTF-8"))
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// The rest of your code

Related

How to post x-www-form-urlencoded post request?

I am having troubles with posting http POST request in java. All the details are correct, but I am getting error for not valid API key.
I tried everything, and read every single post that I could find here but still no clue what is incorrect.
Here's the code:
String urlString = "https://example.com/";
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("api_key", "UTF-8")
+ "=" + URLEncoder.encode("xxxxx", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
try{
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
System.out.println(result);
} catch (IOException e){
throw(new Throwable("An error occured:\n" + e));
}

EDIT: How do I send this post Request with parameters AND form-data like this postman screenshot in JAVA?

I'm trying to send a POST request to grab comments but it doesn't work in Java while it does work with postman.
I get an 403 Forbidden error, but on postman it retrieves the data i need just fine..
Here's the Java code I'm trying to use to replicate the behavior.
String targetUrl = YOUTBE_COMMENTS_AJAX_URL;
String urlParameters = "action_load_comments=1&order_by_time=True&filter=jBjXVrS8nXs";
String updatedURL = targetUrl + "?" + urlParameters;
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(updatedURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("content-type", "multipart/form-data");
urlConnection.setRequestProperty("user-agent", "USER_AGENT");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("video_id", "UTF-8")
+ "=" + URLEncoder.encode(youtubeId, "UTF-8");
data += "&" + URLEncoder.encode("session_token", "UTF-8") + "="
+ URLEncoder.encode(xsrfToken, "UTF-8");
data += "&" + URLEncoder.encode("page_token", "UTF-8") + "="
+ URLEncoder.encode(pageToken, "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
Here's an example of what postman is sending in their headers
It seems like your problem is here (see inline comments):
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
// you wrote your URL parameters into Body
wr.flush();
wr.close();
//You closed your body and told server - you are done with request
conn.getOutputStream().write(postDataBytes);
// you wrote data into closed stream - server does not care about it anymore.
You have to append your urlParameters directly to the URL when you open it
Then you have to write your Form Data into body as you do:
conn.getOutputStream().write(postDataBytes);
and then close output stream

HttpURLConnection error: java.net.SocketTimeoutException: Connection timed out

I am using simple urlconnection like this:
url = URL+"getClient&uid="+cl_id;
URL url = new URL(this.url);
Log.d("Set++","get_t URL: "+ url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
its working fine, but sometimes i get this error:
error: java.net.SocketTimeoutException: Connection timed out
what could be the reason? I have only 4 clients... so i dont think that the server is overloaded with connections.
the code:
try {
URL = Settings.BASE_URL + "_interface.php?" +
"key=" + Settings.KEY +"&app_naam="+Settings.APP_NAAM+ "&action=check&setTime="+c;
URL url = new URL(URL);
if(D)Log.e("ChekTreadAanvr+url", URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String response;
if ((response = rd.readLine()) != null) {
rd.close();
}
if(D) Log.d("WebSaveThread+","DATARESIEVED: "+response);
return response;
} catch (MalformedURLException e) {
if(D)Log.d("ERR","server chekc failure ++ ");
return success = false;
} catch (IOException ioex) {
if(D)Log.e("ERR", "error: " + ioex.getMessage(), ioex);
success = false;
}
return Boolean.toString(success);
It may be possible that your Internet Connection Speed is weak. You can increase your Timeout Interval by using following method.
httpURLConnection.setConnectTimeout( 6 * 10 * 1000 ); // One Minute
If you are connecting to a particularly slow server, there are two timeouts that you can set: setConnectTimeout() and setReadTimeout(). The names are fairly self explanatory. For example:
httpURLConnection.setConnectTimeout(60*1000);
httpURLConnection.setReadTimeout(60*1000);

set methods aren't working for HttpsURLConnection

I'm trying to make a rest request in java. I tested the web service using RestClient in Firefox and it works great.
When i try to modify the HttpsUrlConnection instance in java the values aren't changing and i get a 500 response code.
Here's my code:
public String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;
}
I'm stucked at this point and cannot find anything to make this work.
Thank you!
I actually think it's a bug with HttpsURLConnection. As i changed it to a HttpURLConnection object everything works just fine.

How to set Content Length REST Request - for Android

I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.
public static String getSiteToken(String host,String token) throws IOException, JSONException
{
host = host.replace("https://", "http://");
URL url = new URL(host + "/tokens");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", token);
conn.setRequestProperty("Content-Length", "57");
//conn.setFixedLengthStreamingMode(57);
conn.setRequestProperty("Connection","keep-alive");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
JSONObject json = new JSONObject(rd.readLine());
rd.close();
conn.disconnect();
return json.getString("token");
}
I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!
You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57

Categories