I currently use a Linux Shell Script below
shell_exec("wget --output-document=/var/www/html/kannel/rresults/".$file.".res --post-file=/var/www/html/kannel/rbilling/".$file." --http-user=user1 --http-password=pass1 --header=\"Content-Type: text/xml\" 77.203.65.164:6011");
This shell script uses wget from linux to execute the url with basic authentication and uploads a file.
I want to convert this to java so that it will:
Connect
Authenticate
Post XML file
Also, is it possible to authenticate once and then post as many file as I want?
UPDATE....................
I tried the code below
public class URLUploader {
public static void main(String[] args) throws IOException
{
URL url = new URL("http://77.203.65.164:6011");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
String name = "user";
String password = "password";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}
}
i tried the code above go the error:
auth string: optiweb:optiweb
Base64 encoded auth string: b3B0aXdlYjpvcHRpd2Vi
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: 77.203.65.164:6011
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
at URLUploader.main(URLUploader.java:32)
what could be wrong?
You can use Apache HttpComponents for this.
Here's an example for client authentication
package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
Here's an example that does an upload
public void testUpload() throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(myUploadUrl);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("string_field",
new StringBody("field value"));
FileBody bin = new FileBody(
new File("/foo/bar/test.png"));
reqEntity.addPart("attachment_field", bin );
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String page = EntityUtils.toString(resEntity);
System.out.println("PAGE :" + page);
}
}
You need to supply the correct http basic auth headers with your request. In Java, you can do this by encoding the username:password and passing them with your request:
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", Base64.encode(username+":"+password));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
where "data" contains the content you want to post to the server.
Related
I'm trying to Client Credentials Flow authenticate but keep returning error 400. I've taken a look at the available APIs but I can't see what I'm doing wrong. If somebody could give me a nudge in the right direction that would be fantastic. Thanks
package com.elliott.lyric.io;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import static org.apache.http.protocol.HTTP.USER_AGENT;
/**
* Created by elliott on 05/05/2017.
*/
public class SpotifyLoader {
String nowPlayingURL = "https://api.spotify.com/v1/me/player/currently-playing";
String authURL = "https://accounts.spotify.com/api/token?grant_type=client_credentials";
String clientID = "";
String secretID = "";
String authScope = "user-read-currently-playing user-read-playback-state";
public SpotifyLoader() {
authorize();
//getRawPlaying();
}
void authorize() {
try {
HttpClient client = HttpClientBuilder.create().build();
System.out.println(authURL);
HttpPost post = new HttpPost(authURL);
// add header
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<>();
String idSecret = clientID + ":" + secretID;
String idSecretEncoded = new String(Base64.encodeBase64(idSecret.getBytes()));
urlParameters.add(new BasicNameValuePair("Authorization", "Basic " + idSecretEncoded));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
}
}
void getRawPlaying() {
}
}
Try the request with below changes
Move the query string from url to request body so the URL is https://accounts.spotify.com/api/token
send authorization in header. I just modified the authorize() as below.
void authorize() {
try {
authURL = "https://accounts.spotify.com/api/token";
String idSecret = clientID + ":" + secretID;
String idSecretEncoded = new String(Base64.encodeBase64(idSecret.getBytes()));
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(authURL);
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Authorization", "Basic " + idSecretEncoded);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Using http in java (eclipse) I have to POST a message using a given url with header of http authorization as 64 base encoded message and body has the information like grant type,password,username ,scope.There is a given content type,password,username.I want the client code and using it I should be able to get the message from the server and show that message as the output.
Here is a sample code
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setConnectTimeout(timeout);
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream ());
wr.write(requestString);
wr.flush ();
wr.close ();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.t
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpClassExample {
public static void main(String[] args) throws Exception {
HttpClassExample http = new HttpClassExample();
System.out.println("Testing Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String userName="world#gmail.com";
String password="world#123";
String url = "https://world.com:444/idsrv/issue/oauth2/token";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String ClientId = "mmclient";
String ClientSecret = "norZGs5vkw+cmlKROazauMrZInW9jokxIRCmndMwc+o=";
String userpass = ClientId + ":" + ClientSecret;
String basicAuth = "Basic "+" "
+ javax.xml.bind.DatatypeConverter.printBase64Binary(userpass
.getBytes());
con.setRequestProperty("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","Application/x-www-form-urlencoded");
String urlParameters = "grant_type=password&username="+userName+"&password="+password+"&scope=urn:meetingmanagerservice";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
I have a code written in java for android app. by using HttpPost and DefaultHttpClient library. Currently, i am recoding it to replace the HttpPost and DefaultHttpClient library with HttpURLConnection, as DefaultHttpClient has been depricated.
I have done it for one my project, and it worked.
But in the current project I am not getting same response from the webservice upon using HttpURLConnection instead of DefaultHttpClient. Would any one help me please where I'm doing mistake?
Here is the old code:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
try {
httpPost.setEntity(new StringEntity(postParameter));
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
And here is my new code
_Url = new URL(Url);
HttpURLConnection urlconnection = (HttpURLConnection) _Url.openConnection();
urlconnection.setRequestMethod(Type);
urlconnection.setConnectTimeout(Timeout);
urlconnection.setUseCaches(false);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os));
writer.write(postParameter);
writer.flush();
writer.close();
os.close();
urlconnection.connect();
The code is running without any error, but the webservice is not giving same response as it is giving for the old code.
You are not getting the input stream, try the below code
try {
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
URL url = new URL(UrlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept",
"application/json");
urlConnection.setRequestProperty("Content-Type",
"application/json");// setting your headers its a json in my case set your appropriate header
urlConnection.setDoOutput(true);
urlConnection.connect();// setting your connection
OutputStream os = null;
os = new BufferedOutputStream(
urlConnection.getOutputStream());
os.write(postParameter.toString().getBytes());
os.flush();// writing your data which you post
StringBuffer buffer = new StringBuffer();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
// reading your response
is.close();
urlConnection.disconnect();// close your connection
return buffer.toString();
} catch (Exception e) {
}
try this
List nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("Param1", value1));
nameValuePairs.add(new BasicNameValuePair("Param2", value2));
nameValuePairs.add(new BasicNameValuePair("Param3", value3));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
OutputStream post = request.getOutputStream();
entity.writeTo(post);
post.flush();
I want to make a java program to auto login at http://www.eclass.teikal.gr/eclass2/
When I run this I take as result the same page! Where am I doing wrong ?
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
// String url = "https://selfsolve.apple.com/wcResults.do";
String url = "http://www.eclass.teikal.gr/eclass2/index.php";
URL obj = new URL(url);
URL obj1 = new URL ("http://www.eclass.teikal.gr/eclass2/");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
HttpURLConnection con1 = (HttpURLConnection) obj1.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "uname=my_username&pass=my_password&submit=";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
Try to submit this request from some other tool, for example firefox plugin HTTP Resource test. Then you will find if the problem is in your request or in your code.
I've this code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class Demo2 {
public static void main(String[] args) {
try {
String url = "http://www......";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
System.out.println("Redireccionando...");
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
System.out.println("Galletas: " + cookies);
// open the new connnection again
conn = (HttpsURLConnection) new URL(newUrl).openConnection();
conn.setFollowRedirects(true);
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
System.out.println("Redirect to URL : " + newUrl);
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and result is:
Request URL ... "http://www.web1.com"
Response Code ... 302
Redireccionando...
Galletas: 07c18a1bea3520c44535aafeeea31dec07a36313;
path=/
Redirect to URL : "https://www.web2.com"
java.net.ProtocolException: Server redirected too many times (20) at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1635)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at Demo2.main(Demo2.java:58)
What is the problem? I'm going crazy
I also encountered the same issue and this fix, helped me to overcome it.
before calling the openConnection(); use the following:
HttpURLConnection.setFollowRedirects(false);
I was facing same issue. Even I spent quite a lot amount of time to fix this issue.
I found out that issue was coming to due following:
When you make a call to some JSON services, sometime services might return you data in raw formats or format which may not be typical application/json.
Your .openConnection() or InputStreamReader may not be able to read reponse headers and JSON data.
To fix this issue I tried following and it worked for me:
Used HttpClient httpClient = new DefaultHttpClient(); instead of
(HttpURLConnection) obj.openConnection();
Set allow circular redirect:
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
true);
Set following post headers which is important:
httpPost.setHeader("charset","utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language","en-US,en;q=0.8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
Use StringEntity Read input stream with UTF-8:
httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);
Here is the sample code which worked for me:
HttpClient httpClient = new DefaultHttpClient();
String url =http://....; httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("charset","utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language","en-US,en;q=0.8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//or you can try httpPost.setContentType("application/x-www-form-urlencoded");
StringEntity requestBody = new StringEntity(jsonBody);
requestBody.setContentType("application/json");
httpPost.setEntity(requestBody);
HttpResponse httpresponse = httpClient.execute(httpPost);
org.apache.http.StatusLine statusRespons = httpresponse.getStatusLine();
if (statusRespons.getStatusCode() > 201)
{
errorText = statusRespons.getStatusCode() + " : " + statusRespons.toString() + " : " +statusRespons.getReasonPhrase() ;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);
String s = "";
while ((s = buffer.readLine()) != null)
jsonString.append(s);
Hope this helps you?