Anything wrong with this code.. If I add this line (String c= t.parseToString(content);) below the Ti t = new Ti(); then I get the actual content of the url back but after that I get null values for Keywords, Title and Authors. And If I remove this line (String c= t.parseToString(content);) then I get the actual values for Title, Author and Keywords.. Why is it so??
HttpGet request = new HttpGet("http://xyz.com/d/index.html");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
System.out.println(content)
Ti t = new Ti();
String ct= t.parseToString(content);
System.out.println(ct);
Metadata md = new Metadata();
Reader r = t.parse(content, md);
System.out.println(md);
System.out.println("Keywords: " +md.get("keywords"));
System.out.println("Title: " +md.get("title"));
System.out.println("Authors: " +md.get("authors"));
You are reading the same stream multiple times. After you read a stream fully, you cannot read it again. Do something like,
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
//http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java
byte[] content = streamToByteArray(entity.getContent());
String ct = t.parseToString(new ByteArrayInputStream(content));
System.out.println(ct);
Metadata md = new Metadata();
Reader r = t.parse(new ByteArrayInputStream(content), md);
System.out.println(md);
Related
Using HttpEntity I am getting a very long text which has special characters as well along with Json.
I tried regex but it's not working as it is almost 30000 of characters.
Is there a way that i can only get Json data from the HttpEntity. Even string split did not work since it has so many of special characters.
public JSONObject sendGet(String URL, String userName, String password) throws Exception {
getRequest = new HttpGet(URL);
getRequest.addHeader("User-Agent", USER_AGENT);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
outputFile = new File(directoryPath + "/target/response.txt");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header: headers) {
bw.write(header.getName() + ": " + header.getValue() + "\n");
}
bw.write(response.getEntity());
bw.write("Response Code : " + response.getStatusLine());
String content = EntityUtils.toString(entity); //When i print content it has string other than json as well
JSONObject obj = new JSONObject(content); //Here i receive A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONArray keys = obj.names();
Object test = JSON.parse(content);
jsonFiles = new File(directoryPath + "/JsonFiles/test.json");
fos = new FileOutputStream(jsonFiles);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
bw.close();
return obj;
}
Try adding the following Headers:
getRequest.addHeader("Accept", "application/json");
getRequest.addHeader("Content-Type", "application/json");
getRequest.addHeader("Accept-Charset", "utf-8");
I am creating an application where I need to get file attached in mail and then send that complete file as input of another API of portal called 'asana'. I don't want to save/ download the file locally.
I referred this site to get the attached file through mail.
But, I need to send the file to 'asana' API without downloading it.
Here is the code of asana API to send file through API.
String url = "https://app.asana.com/api/1.0/tasks/"+asanaActivitiesDto.getTaskId()+"/attachments";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Bearer " + asanaActivitiesDto.getBearerToken());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("task", jsonInput.get("taskId").toString(), ContentType.TEXT_PLAIN);
// now here I actually want file from attachment of the mail
// currently taking file from local for testing
File f = new File(asanaActivitiesDto.getFile());
builder.addBinaryBody(
"file",
//Here, as a second input, I need to set file from the
//attachment of the mail
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
post.setEntity(multipart);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
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);
}
System.out.println(result.toString());
JSONParser parser = new JSONParser();
jsonOutput = (JSONObject) parser.parse(result.toString());
at the place of new FileInputStream(f), I need to send file attached to that mail. What are the possible ways to do the same?
You can just read the data in the email attachment as an InputStream. Try something like:
mbp = // the MimeBodyPart containing the attachment
builder.addBinaryBody(
"file",
mbp.getInputStream(),
ContentType.APPLICATION_OCTET_STREAM,
mbp.getFileName()
);
Below is the Http post method for file upload in c#. What is the equivalent for this code in java which uses apache library. How to add contentDisposition in java and pass byte array value in it. Providing some online reference is much appreciated.
C# Code
byte[] date = //file in byte format
var fileContent = new StreamContent(new MemoryStream(data));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + filename + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
var content = new MultipartFormDataContent();
content.Add(fileContent);
HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _url + uri);
request.Content = content;
My Java Code
StringBody name = new StringBody("\"files\"", ContentType.MULTIPART_FORM_DATA);
StringBody file = new StringBody("\"" + filename + "\"", ContentType.MULTIPART_FORM_DATA);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("Name", name)
.addPart("FileName", file)
.addBinaryBody("file", data)
.build();
Postmethod = new HttpPost(_url + uri);
Postmethod.addHeader(useragent);
Postmethod.addHeader(Accesstoken);
Postmethod.setEntity(entity);
Postmethod.addHeader("content-type", contentType);
response = httpClient.execute(Postmethod);
The response status code is 400 .Where did I go wrong?
Thanks in Advance..
I have this code to post data to my server:
// HTTP Settings
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://myserver.com/Login");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// Http Headers
postRequest.addHeader("Accept", "application/xml");
postRequest.addHeader("Connection", "keep-alive");
// Credentials
reqEntity.addPart("username", new StringBody(ServerData.username));
reqEntity.addPart("password", new StringBody(ServerData.password));
if (m_sigFile.exists()) {
Bitmap m_sig = BitmapFactory.decodeFile(sigFilePath
+ "m_sig.jpg");
ByteArrayOutputStream m_bao = new ByteArrayOutputStream();
m_sig.compress(Bitmap.CompressFormat.JPEG, 90, m_bao);
byte[] m_ba = m_bao.toByteArray();
String m_ba1 = Base64.encodeToString(m_ba, 0);
reqEntity.addPart("m_sig.jpg", new StringBody(m_ba1));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
The code works perfectly, all data is send to the server except for the jpeg file. The server only accepts the file if I set the content type to 'image/jpeg', but only for the image. The username and password has to be in plain text. Is this possible?
This will work:
ContentBody cbFile = new FileBody(new File(myPath
+ "image_1.jpg"),
"image/jpeg");
reqEntity.addPart("photo1"), cbFile);
Don't forget to check if you file exists!
There is a constructor for StringBody that accepts content type:
new StringBody(titleString, "application/atom+xml", Charset.forName("UTF-8"));
So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());