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();
}
}
But I got the following 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?
First, HTTP Response Code 500 is "Internal Server Error" and has nothing to do with authentication.
Second, the statement
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
just writes the file's full pathname to the server, not the actual file contents, without even a trailing newline. This is certainly not what the server is expecting, and may be the cause of the 500 response. The request you are building and sending may have other problems as well, but without a detailed API reference for whatever's on the other end of the connection, it will be hard to provide further help.
Related
I want to use the MailChimp api to add a subscriber. As a start, want to read from one of the REST I'm trying to get a response back from the MailChimp api.
I seem to be doing the authorization correctly as I'm getting status 200, but for some reason, I am not getting the response.
Here is the code so far:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
Looking at the MailChimp playground, it seems like I'm missing out on a lot...
How do I get the response?
****/ EDIT /****
If anyone's looking at the above code, the output should be:
System.out.println("DoPost response: \n" + sb); // not line
OK, the above code works. Basic error.
I was examining the line variable when it was null, not the response...
When I change to:
System.out.println("DoPost response: \n" + line); // not line
System.out.println("DoPost response: \n" + sb); // but sb StringBuilder
...it works.
I would like a Send an authentication request to Google.
But I get the error: Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL.
Can someone help me and say where the error lies?
My code looks as follows:
public class Main
{
public static void main( String... args ) throws Exception
{
String httpsURL ="\n" +
" client_id=xxx.apps.googleusercontent.com&\n" +
" response_type=code&\n" + // "code" is an Basic Value
" scope=openid%20email&\n" +
" redirect_uri=http://localhost&\n" +
" state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2-login-demo.example.com/myHome&\n" +
" login_hint=peterpan#googlemail.com\n";
String inputLine;
String httpsencode ="https://accounts.google.com/o/oauth2/v2/auth?" + URLEncoder.encode(httpsURL, "UTF-8");
URL u = new URL(httpsencode);
HttpsURLConnection con = (HttpsURLConnection)u.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
Try to remove all yours "\n" in httpsURL.
You don't need new line char between 2 GET arguments.
Edit : http error code 400 explained here : http://www.checkupdown.com/status/E400.html
I'm doing something about sending http REST request to Teamcity server.
For the authentication part, when I use code below, I will get the 401 error.
public class Client {
public static void main(String args[]){
try{
Client client = new Client();
client.sendGet();
//client.sendPost();
}catch(Exception e){
e.printStackTrace();
}
}
String USER_AGENT = "";
private void sendGet() throws Exception {
String url = "http://localhost:80/httpAuth/app/rest/builds";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
String login = "gearon";
String password = "gearonpassword";
String token = login + ":" + password;
con.setRequestProperty ("Authorization", "Basic " + token);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
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();
System.out.println(response.toString());
}
}
I solve the problem by adding below code
byte[] tokenArr = StringUtils.getBytesUtf8(token);
String encoded = new String(Base64.encodeBase64(tokenArr));
con.setRequestProperty ("Authorization", "Basic " + token);
However, I can't figure out why this solved my problem. There is no any special character in my username or password. And, I have set my project encoding to UTF-8 in Eclipse by Right click the project --> Properties --> Resources --> Text file encoding --> UTF-8.
The javadoc of getBytesUtf8 method is
Encodes the given string into a sequence of bytes using the UTF-8
charset, storing the result into a new byte array.
If my project is using UTF-8 already, this method should add no value.
For another method encodeBase64, the javadoc is:
Encodes binary data using the base64 algorithm but does not chunk the
output.
Maybe there is where amazing happens. I read something about Base64 in wiki
I can't make myself clear about this issue. So could anybody tell me what happened behind.
This is defined in RFC 7617:
To receive authorization, the client
obtains the user-id and password from the user,
constructs the user-pass by concatenating the user-id, a single
colon (":") character, and the password,
encodes the user-pass into an octet sequence (see below for a
discussion of character encoding schemes),
and obtains the basic-credentials by encoding this octet sequence
using Base64 ([RFC4648], Section 4) into a sequence of US-ASCII
characters ([RFC0020]).
I want to integrate MailChimp API in my java project. When I call Rest call using HttpURLConnection class, it responds with 401 code.
Here is my code:
URL url = new URL("https://us13.api.mailchimp.com/3.0/lists");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "apikey <my-key>");
String input = "<json data>";
OutputStream os = conn.getOutputStream();
//os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I will suggest using Apache Commons Codec package for encoding.
It support various formats such as Base64 and Hexadecimal.
Earlier I was also facing the same issue. I am sharing the code that I used in my application for authenticating to Mailchimp API v-3.0
//basic imports
import org.apache.commons.codec.binary.Base64;
.
.
.
//URL to access and Mailchimp API key
String url = "https://us9.api.mailchimp.com/3.0/lists/";
//mailchimp API key
String apikey = xxxxxxxxxxxxxxxxxxxxxxxxxxx
// Authentication PART
String name = "Anything over here!";
String password = apikey; //Mailchimp API key
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is1 = httpConnection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is1, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Now you can use StringBuilder Object sb to parse the output as required
Hope it resolves your issue :)
HTTP 401 response code means "not authorized".
You didn't set or pass your credentials properly. Is the certificate from the client set up? Here's an example of an HTTPS client.
HTTP 401 simply means you're not Authorized to send this request.
you can set username any string (the MailChimp docs suggest using anystring as a username) and your API key as a password.
In case of Postman request, you can set under the Authorization tab choose Basic Auth to set username and password. Below image shows the same.
More info about Adding/ Getting Members to/ from a Mailing List on MailChimp API 3.0, I find this article very useful.
I am trying to get content from the website Socialcast which needs authentication. (First I do a HTTP Post with Basic Authentication and then I try a HTTP GET).
I tried several codes, I receive this as "result":
emily#socialcast.com:demo
Base64 encoded auth string: ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw==
* BEGIN
You are being redirected.
END *
Here is the code for HTTP Basic Auth:
try {
String webPage = "http://demo.socialcast.com";
String name = "emily#socialcast.com";
String password = "demo";
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);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
However, when I try to do a GET afterwards, it says unauthorized.
The credentials are emily#socialcast.com/demo - those are provided by Socialcast Dev at the moment, as I also cannot access my own Socialcast instance.
Is this code wrong? How can I do it properly? BTW, I am using HttpClient 4.x.
Are you sending the credentials in each request? I think this is needed, otherwise the server does not have any other information to prove that you still are authorized to view other pages...
I'm not sure why this question is tagged with apache-httpclient-4.x when your example code doesn't use it. In fact, if you do use httpclient then you can get it to handle authentication for you quite easily, see here for the excellent tutorial.