How to download unirest post call response in java? - java

String jsonBody = "<Json input>";
HttpResponse<String> response = null;
RequestBodyEntity res=null;
String url = "<some url>";
try {
response = Unirest.post(url).header("content-type", "application/json").body(jsonBody).asString();
System.out.println("Response: " + response.getBody());
} catch (UnirestException e) {
Reporter.reportStatus("Fail", "Failure in Unirest call", "path is "+url);
}
File file = new File("<Location of the file>");
InputStream input = response.getRawBody();
try {
FileOutputStream report = convertInputStreamToFile(input, file);
} catch (Exception e) {
e.printStackTrace();
}
I want to get some response to this post call that will be stored in "response".
I want to download the response, preferably to an excelsheet.
How do I go about it?

Related

Java URL downloading HTML content instead of file?

I am trying to download file using Java URL class, but it is downloading HTML content instead.
class DownloadFileHttpCilent {
public static void main(String[] args) throws Exception {
try {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(
"https://url");
String encoding=Base64.getEncoder().encodeToString(("abcd:pwd").getBytes());
request.setHeader("Authorization", "Basic " + encoding);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Request Url: " + request.getURI());
System.out.println("Response Code: " + responseCode);
InputStream is = entity.getContent();
String filePath = "c:\\file1.zip";
FileOutputStream fos = new FileOutputStream(new File(filePath));
int inByte;
while ((inByte = is.read()) != -1) {
fos.write(inByte);
}
is.close();
fos.close();
client.close();
System.out.println("File Download Completed!!!");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
For other open source URLs, it's working fine, but only in this case, in which it is password protected, it is downloading HTML content.
Output:
Request Url: https://abcd.cahj.com/defj
Response Code: 200
File Download Completed!!!

Can't use google to log users into dropbox

I am building a app that allows interaction with Dropbox. I have successfully authenticated to, and Dropbox is returning a key and template using it's default login page. However, when I try to use the login with Google option for Dropbox upon authenticating Dropbox returns a user key, however it doesn't return a template id, but instead a too many templates error.
Any help would be appreciated.
Here is my code
public void authUrl(HttpServletRequest request)
{
DbxWebAuth webAuth = new DbxWebAuth(requestConfig, appInfo);
HttpSession session = request.getSession(true);
String sessionKey = "dropbox-auth-csrf-token";
DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey);
DbxWebAuth.Request authRequest = DbxWebAuth.newRequestBuilder()
.withRedirectUri(redirectUri, csrfTokenStore)
.build();
String authorizeUrl = webAuth.authorize(authRequest);
url =authorizeUrl;
}
public String getTemplate()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.dropboxapi.com/2/file_properties/templates/add_for_user");
post.addHeader("Authorization","Bearer "+code);
post.addHeader("Content-Type", "application/json");
try {
HttpEntity entity = new StringEntity(json);
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
if (entity != null) {
InputStream instream = entity.getContent();
try {
Scanner s = new Scanner(instream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
System.out.println(result);
System.err.println(result);
return result;
} finally {
instream.close();
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public String authcode(HttpServletRequest request)
{
DbxWebAuth auth = new DbxWebAuth(requestConfig, appInfo);
String sessionKey = "dropbox-auth-csrf-token";
HttpSession session = request.getSession(true);
DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey);
DbxAuthFinish authFinish;
try {
authFinish = auth.finishFromRedirect(redirectUri, csrfTokenStore, request.getParameterMap());
} catch (DbxWebAuth.BadRequestException ex) {
System.out.println("On /dropbox-auth-finish: Bad request: " + ex.getMessage());
return "failed";
} catch (DbxWebAuth.BadStateException ex) {
System.out.println(ex.getMessage());
// Send them back to the start of the auth flow.
return "failed";
} catch (DbxWebAuth.CsrfException ex) {
System.out.println("On /dropbox-auth-finish: CSRF mismatch: " + ex.getMessage());
//response.sendError(403, "Forbidden.");
return "failed";
} catch (DbxWebAuth.NotApprovedException ex) {
// When Dropbox asked "Do you want to allow this app to access your
// Dropbox account?", the user clicked "No".
//...
return "failed";
} catch (DbxWebAuth.ProviderException ex) {
System.out.println("On /dropbox-auth-finish: Auth failed: " + ex.getMessage());
//response.sendError(503, "Error communicating with Dropbox.");
return "failed";
} catch (DbxException ex) {
System.out.println("On /dropbox-auth-finish: Error getting token: " + ex.getMessage());
//response.sendError(503, "Error communicating with Dropbox.");
return "failed";
}
String accessToken = authFinish.getAccessToken();
code =accessToken;
return accessToken;
}
Notes
I am using a java, running on a google app engine server to complete this authentication.
The exact error text in the logs is
{"error_summary": "too_many_templates/...", "error": {".tag":
"too_many_templates"}}
Along with a error 409.
If you need any more information feel free to ask

How can i create user in salesforce through REST api? Give me some examples

Am trying to create user into my salesforce account through REST api using java.But its returning 400 status code.Can you please guide me?
Here is the code am trying:
public static void createUsers() {
System.out.println("\n_______________ USER INSERT _______________");
String uri = baseUri + "/sobjects/User/";
System.out.println(uri);
try {
//create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("FirstName", "Jake");
lead.put("LastName", "sully");
lead.put("Alias", "Jake");
lead.put("Email", "Jake#gmail.com");
lead.put("Username", "Jake#gmail.com");
lead.put("Name", "jake");
lead.put("UserRoleId","00E28000000oD8EEAU");
lead.put("Id", "10028000000GLSIAA4");
lead.put("EmailEncodingKey", "ISO-8859-1");
lead.put("TimeZoneSidKey", "Asia/Kolkata");
lead.put("LocaleSidKey", "en_US");
lead.put("ProfileId", "00e280000027hnGAAQ");
lead.put("LanguageLocaleKey", "en_US");
//Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
System.out.println(response.toString());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved lead id to use when we update the lead.
leadId = json.getString("id");
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}

POST httpRequest doesn't fetch all data

I use the following function in java to connect to my php script in a server.
The script queries for an image (BLOB), encodes it (base64) and sends it back in JSON format.
The problem is that I can get some of the encoded data but not all of them. Should I use any headers on my httpRequest? What am I doing wrong?
Here is my java function:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("Print1: "+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return null;
}
System.out.println("Print2: "+jObj.toString());
// return JSON String
return jObj;
}
Here is my PHP code showing the JSON structure:
$response = array(
"success" => 0,
"message" => "",
"data" => "");
$stmt->bindColumn(1, $binary, PDO::PARAM_LOB);
$stmt->bindColumn(2, $professorName);
$stmt->fetch(PDO::FETCH_BOUND);
$pic = base64_encode($binary);
$data = array(
"photo" => $pic,
"professorName" => $professorName
);
$response["success"] = 1;
$response["message"] = "We have results!";
$response["data"] = $data;
echo json_encode($response);
After testing I realized that if I use a small image (tested size < 1Kb) everything works as it should.
If I try to obtain a larger image (here 5 Kb) the data I obtain is cut in the middle.
The json structure doesn't arrive complete.
Here is an example of a successful transfer:
Print1: {"success":1,"message":"We have results!","data":
{"photo":"iVBORw0KGgoAAAANS~~~~more data~~~~N6GGYzAAAAAElFTkSuQmCC","professorName":"cluvas"}}
Print2: {"data":{"kathigitisName":"cluvas","photo":"iVBORw0K~~~~more data~~~~AElFTkSuQmCC"},
"message":"We have results!","success":1}
Here an example of an unsucessful one
Print1: {"success":1,"message":"We have results!","data":
{"photo":"\/9j\/4AAQS~~~~more data~~~~6KKogkH\/ //unexpected end of data
Print2: {"data":{"professorName":"cluvas",
"photo":"\/9j\/4AAQS~~~~more data~~~~K+U\/Ce //unexpected end of data

Read json object from server

Hi I am new to android programming and I am working on a project that converts a list into json object and stores it in the server and retrieves it. I am able to send the json object to the server and store it but i am not able to retrieve it. What approach should i use to retrieve the json object stored on the server?
You can reffer bellow class ...... call getJSONfromURL(YOUR_JOSN_URL) and method will return you JSONObject.
I hope this will work
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
To retrieve JSON from server you have to establish a connection with server first by using DefaultHttpClient Hope you did that. If yes, post your code and if no then have look on
www.androidhive.info/2012/01/android-json-parsing-tutorial
Or google it you will lot of help to parse the JSON when you have URL with you.

Categories