Https request, authentication in Android - java

I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.
In Android I am returning inputLine in a function, however inputLine is always an empty string.
The system.out.println() prints the returned token.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class JavaHttpsExample
{
public static void main(String[] args)
{ String inputLine = new String();
try
{
String httpsURL = "https://the url";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
thanks for your help!!!

You probably did not add the Internet-Permission to your projects AndroidManifest.xml.
If so, add the following line as a child of the <manifest/> node:
<uses-permission android:name="android.permission.INTERNET" />

I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:
final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);
//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);
//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]
maybe you'll find this usefull

Related

Make an HttpPost with params and Body

I need to replicate a Postman POST in Java.
Usually I had to make an HttpPost with only params in URL, so it was easy to build:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
But what I have to do if I have a POST like the image below where there are Params in URL and Body TOGETHER??
Now I'm making the HttpPost like this:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
HttpResponse httpResponse = client.execute(post);
//Do something
}catch (Exception e){
//Do something
}
But how I put "filename" and "filedata" params in the Body together with the params in the URL?
Actually I'm using org.Apache library, but i could consider also others library.
Thanks to anybody that will help!
You can use below code to pass the body parameters as "application/x-www-form-urlencoded" in POST method call
package han.code.development;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpPost
{
public String getDatafromPost()
{
BufferedReader br=null;
String outputData;
try
{
String urlString="https://www.google.com"; //you can replace that with your URL
URL url=new URL(urlString);
HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Authorization", "Replace with your token"); // if you have any accessToken to authorization, just replace
connection.setDoOutput(true);
String data="filename=file1&filedata=asdf1234qwer6789";
PrintWriter out;
if((data!=null))
{
out = new PrintWriter(connection.getOutputStream());
out.println(data);
out.close();
}
System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb=new StringBuilder();
String str=br.readLine();
while(str!=null)
{
sb.append(str);
str=br.readLine();
}
outputData=sb.toString();
return outputData;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
HttpPost post=new HttpPost();
System.out.println(post.getDatafromPost());
}
}
I think this question, and this question are about similar issues and both have good answers.
I would recommend using this library as it is well maintained and simple to use if you want.
I've resolved making this way:
put on POST URL header params;
adding as MultipartEntity the filename and filedata.
Here the code....
private boolean uploadQueue(String username, String password, String filename, byte[] fileData)
{
HttpClient client = HttpClientBuilder.create().build();
String URL = "http://post.here.com:8080/";
HttpPost post = new HttpPost(URL +"?username="+username+"&password="password);
try
{
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addBinaryBody("filedata", fileData, ContentType.DEFAULT_BINARY, filename);
entityBuilder.addTextBody("filename", filename);
post.setEntity(entityBuilder.build());
HttpResponse httpResponse = client.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return true;
}
else
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return false;
}
}
catch (Exception e)
{
logger.error("Error during Updload Queue phase:"+e.getMessage());
}
return false;
}

Sending Json POST to server using name value pair

I am sending Json Post request to server to through url: http://www.xyz.com/login
request structure:
{"requestdata":{"password":"abc","devicetype":"phone","username":"amrit#pqr.com","locale":"in"},"requestcode":10}
Code Snapshot:
MainActivity:
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("requestcode", "10"));
nameValuePair.add(new BasicNameValuePair("devicetype", "phone"));
nameValuePair.add(new BasicNameValuePair("locale", "in"));
nameValuePair.add(new BasicNameValuePair("username", "amrit#pqr.com"));
nameValuePair.add(new BasicNameValuePair("password", "abc"));
RestPost post = new RestPost(loginUrl, nameValuePair);
String Response = post.postData();
Log.i("Response:", Response);
RestPost class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
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.DefaultHttpClient;
import android.util.Log;
public class RestPost {
String url;
List<NameValuePair> nameValuePairs;
public RestPost(String str, List<NameValuePair> params) {
this.url = str;
this.nameValuePairs = params;
}
public String postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
StringBuilder builder = new StringBuilder();
try {
httppost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.d("RestClient", "Status Code : " + statusCode);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return builder.toString();
}
}
But I'm not getting appropriate response, could anyone help me in sending appropriate format for getting server response. Thanks in advance.
Response which I'm getting:
{"error":{"resultCode":"400","status":"Invalid Request format"}}
You are currently sending the JSON in the form of
{
"requestcode": "10",
"devicetype": "phone",
"locale": "in",
"username": "amrit#pqr.com",
"password": "abc"
}
Which isn't the form the server is asking for. Try creating a string of the JSON you want to send. Then use:
httppost.setEntity(new StringEntity(jsonString, "UTF8"));
httppost.setHeader("Content-type", "application/json");
To send the string to the server.
I'm using AndroidHttpClient to post the request
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User Agent");
URL urlObj = new URL(url);
HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
HttpContext credContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost (url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsArrayList));
// Execute post request and get http response
HttpResponse httpResponse = httpClient.execute(host, httpPost, credContext);
httpClient.close();
This works perfectly for me.
AndroidHttpClient http = AndroidHttpClient.new Instance("hai");

How to add,set and get Header in request of HttpClient?

In my application I need to set the header in the request and I need to print the header value in the console...
So please give an example to do this the HttpClient or edit this in my code...
My Code is ,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class SimpleHttpPut {
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://http://localhost:8089/CustomerChatSwing/JoinAction");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("userId",
"123456789"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks in advance...
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
You have something like this:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):
public class App {
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.custom().build();
// (1) Use the new Builder API (from v4.3)
HttpUriRequest request = RequestBuilder.get()
.setUri("https://api.github.com")
// (2) Use the included enum
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
// (3) Or your own
.setHeader("Your own very special header", "value")
.build();
CloseableHttpResponse response = client.execute(request);
// (4) How to read all headers with Java8
List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
httpHeaders.stream().forEach(System.out::println);
// close client and response
}
}

C2DM java example of third-part app

I'm trying to do example form: http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I've got everything allright with android app (I think), but to simulate the
server i all the time got error 403.
The code is the same like in example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class AuthenticationUtil
{
private AuthenticationUtil()
{
}
public static String getToken(String email, String password)
throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=CloudTut");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
}
and the error respond:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.com/accounts/ClientLogin
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at AuthenticationUtil.getToken(AuthenticationUtil.java:48)
at GetAuthenticationToken.main(GetAuthenticationToken.java:8)
This code is from a functioning app and works well for me. It uses the C2DM account login details to request an auth-token, which can then be used to send C2DM messages to client devices. Note that this code is from an Android app, but would typically be executed on the server.
public static String getClientLoginAuthToken() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", "C2DMEMAILADDRESS));
nameValuePairs.add(new BasicNameValuePair("Passwd", "C2DMPASSWORD));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Trace.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Trace.e(TAG, "Failed to get C2DM auth code");
return "";
}
If you continue to have problems, then best to assume the C2DM account wasn't set up right, and create another one.

Posting data in raw format to PHP file and getting response

I am making an android application where I need to send some data collected from a data to server php file using post data and get the echoed text from the php file and display it. I have the post variables in this format -> "name=xyz&home=xyz" and so on. I am using the following class to post, but the php file on the server does not get the post vars. Can someone please tell me whats wrong or any other ways to do what I am trying to do?
package xxx.xxx.xxx;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
public static String UrlToString(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.write(urlParameters.getBytes("UTF-8"));
wr.flush ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
I get a response from php file, but the php file does not get the post data.
The example looks okay to me for a beginner. Only the following springs out:
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
and
wr.write(urlParameters.getBytes("UTF-8"));
In the first you're converting chars to bytes using platform default encoding. The resulting length is not necessarily the same as when using UTF-8 encoding to convert chars to bytes as you did when writing the request body. So the chance exist that the Content-Length header is off from the actual content length. To fix this, you should be using the same charset on the both calls.
But I believe that PHP isn't really that strict when parsing the request body so that you would get nothing in the PHP end. Probably the urlParameters is not in proper format. Are they really URL-encoded?
Anyway, did you try it with Android's builtin HttpClient API? It should be as simple as follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "xyz"));
params.add(new BasicNameValuePair("home", "xyz"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
InputStream input = response.getEntity().getContent();
// ...
If that doesn't work as well, then the mistake is likely in the PHP side.

Categories

Resources