I have to upload a file from my site yet cnt seem to get it working with drop wizard.
Here is the form from my site.
<form enctype="multipart/form-data" method="POST" action="UploadFile">
<input type="file" id="fileUpload" name="file"/>
<input type="hidden" id="fileName" name="fileName"/>
<input type="submit" value="Upload"/>
</form>
How would I go about on the backend to receive the file?
The solution was
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") final InputStream fileInputStream,
#FormDataParam("file") final FormDataContentDisposition contentDispositionHeader) {
String filePath = uploadLocation + newFileName;
saveFile(fileInputStream, filePath);
String output = "File can be downloaded from the following location : " + filePath;
return Response.status(200).entity(output).build();
}
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {
try {
OutputStream outputStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outputStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do the saving to the server in lesser number of lines using nio
java.nio.file.Path outputPath = FileSystems.getDefault().getPath(<upload-folder-on-server>, fileName);
Files.copy(fileInputStream, outputPath);
Also, if you're using 0.7.0-rc2, you will need this dependency in your pom.xml
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.18</version>
</dependency>
With Dropwizard 0.9.2 you have to add the dependency:
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-forms</artifactId>
<version>${dropwizard.version}</version>
<type>pom</type>
</dependency>
as well as register the multipart feature:
environment.jersey().register(MultiPartFeature.class);
Ensure that you add dropwizard-forms dependency to your pom.xml
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-forms</artifactId>
<version>${dropwizard.version}</version>
<type>pom</type>
</dependency>
Your resource seems good, Anyhow I've uploaded an example project for uploading files with Dropwizard - https://github.com/juanpabloprado/dw-multipart
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) throws MessagingException, IOException {
String uploadedFileLocation = "C:/Users/Juan/Pictures/uploads/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.ok(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException {
int read;
final int BUFFER_LENGTH = 1024;
final byte[] buffer = new byte[BUFFER_LENGTH];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
out.close();
}
Related
My download method is
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot" + #"\UploadFiles", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
and view.chtml and route with filepath
<a asp-action="Download"
asp-route-filename="#item.UploadFilePath">
Download
</a>
#item.UploadFilePath is database saved path.please help me.
you can try this also
return File(path, MediaTypeNames.Application.Octet, Path.GetFileName(path));
You can try this,
byte[] fileBytes = System.IO.File.ReadAllBytes(Filepath);
return File(fileBytes, "application/x-msdownload", FileName);
use this code for download file from wwwroot
public IActionResult DownloadAttachment(string attachment)
{
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot\\UploadFile\\Journal",attachment);
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/x-msdownload", attachment);
}
Try this on URL /Files?fileName=image.png, file image.png must be placed in wwwroot.
public class FilesModel : PageModel
{
private readonly IWebHostEnvironment hostingEnvironment;
public FilesModel(IWebHostEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
public PhysicalFileResult OnGet(string fileName)
{
string path = Path.Combine(hostingEnvironment.WebRootPath, "Files", fileName);
return new PhysicalFileResult(path, "image/png"); // Change to the right mime type
}
}
I want to integrate QuickBooks api into our android application.
Below link is for Java Web Application but I want to this OauthHelper class in my android application.
https://github.com/IntuitDeveloperRelations/QuickbooksV3API-Java/blob/master/QuickbooksV3API/src/main/java/com/intuit/utils/OauthHelper.java
I also saw developer site of Intuit but it does not help,
https://intuitpartnerplatform.lc.intuit.com/questions/825445-can-t-find-com-intuit-ia-connection-oauthhelper-class
Is there is a new way to do it or any latest jar file which contain OauthHelper class?
JAR File
You have to add this jar ipp-v3-java-devkit-2.3.2-jar-with-dependencies, you can download from this link.
OauthHelper Class
public class OauthHelper {
public static String REQUEST_TOKEN_URL;
public static String ACCESS_TOKEN_URL;
public static String AUTHORIZE_URL;
public OauthHelper() {
REQUEST_TOKEN_URL = Constants.OAUTH_URL + "/oauth/v1/get_request_token";
ACCESS_TOKEN_URL = Constants.OAUTH_URL + "/oauth/v1/get_access_token";
AUTHORIZE_URL = Constants.APPCENTER_URL + "/Connect/Begin";
}
public void getDynamicConsumer() {
try {
final String apptoken = Constants.APP_TOKEN;
final URL url = new URL(Constants.OAUTH_URL
+ "/oauth/v1/create_consumer?appToken=" + apptoken);
final HttpURLConnection httpconnection = (HttpURLConnection) url
.openConnection();
httpconnection.connect();
StringBuffer responseBody = null;
int read = 0;
final byte buffer[] = new byte[8192];
String consumerret = "";
String consumerkeytoken = "";
String consumerkeysecret = "";
try {
final InputStream responseBodyStream = httpconnection
.getInputStream();
responseBody = new StringBuffer();
while ((read = responseBodyStream.read(buffer)) != -1) {
responseBody.append(new String(buffer, 0, read));
}
responseBodyStream.close();
consumerret = responseBody.toString();
final String[] consumerkey = consumerret.split("&");
for (int i = 0; i < consumerkey.length; i++) {
final String[] currentElements = consumerkey[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
consumerkeytoken = currentElements[1];
} else if (currentElements[0]
.equalsIgnoreCase("oauth_token_secret")) {
consumerkeysecret = currentElements[1];
}
}
} catch (Exception ex1) {
final int httpRespCode = httpconnection.getResponseCode();
try {
final InputStream es = httpconnection.getErrorStream();
final StringBuffer errorBody = new StringBuffer();
while ((read = es.read(buffer)) != -1) {
errorBody.append(new String(buffer, 0, read));
}
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
} catch (Exception ex3) {
ex3.printStackTrace();
}
}
public Map<String, String> getRequestTokenSignPost() {
String authURL = null;
OAuthProvider provider = createProvider();
String consumerkey = Constants.CONSUMER_KEY;
String consumersecret = Constants.CONSUMER_SECRET;
String callback_url = Constants.CALLBACK_URL;// WebUtils.OAUTH_CALLBACK_URL;
OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey,
consumersecret);
try {
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback",
URLEncoder.encode(callback_url, "UTF-8"));
ouathconsumer.setAdditionalParameters(additionalParams);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String requestret = "";
String requestToken = "";
String requestTokenSecret = "";
try {
String signedRequestTokenUrl = ouathconsumer
.sign(REQUEST_TOKEN_URL);
URL url;
url = new URL(signedRequestTokenUrl);
HttpURLConnection httpconnection = (HttpURLConnection) url
.openConnection();
httpconnection.setRequestMethod("GET");
httpconnection
.setRequestProperty("Content-type", "application/xml");
httpconnection.setRequestProperty("Content-Length", "0");
if (httpconnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(
httpconnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
requestret = sb.toString();
}
String[] requestTokenSections = requestret.split("&");
for (int i = 0; i < requestTokenSections.length; i++) {
String[] currentElements = requestTokenSections[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
requestToken = currentElements[1];
} else if (currentElements[0]
.equalsIgnoreCase("oauth_token_secret")) {
requestTokenSecret = currentElements[1];
}
}
Map<String, String> requesttokenmap = new HashMap<String, String>();
try {
authURL = provider.retrieveRequestToken(ouathconsumer,
callback_url);
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
}
ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(),
ouathconsumer.getTokenSecret());
requesttokenmap.put("requestToken", requestToken);
requesttokenmap.put("requestTokenSecret", requestTokenSecret);
requesttokenmap.put("authURL", authURL);
return requesttokenmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static OAuthProvider createProvider() {
OAuthProvider provider = new DefaultOAuthProvider(
OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL,
OauthHelper.AUTHORIZE_URL);
return provider;
}
public String getAuthorizeURL(String requestToken, String requestTokenSecret) {
String authorizeURL = "";
try {
authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
} catch (Exception e) {
e.printStackTrace();
}
return authorizeURL;
}
public Map<String, String> getAccessToken(String verifierCode,
String requestToken, String requestTokenSecret) {
String consumerkey = Constants.CONSUMER_KEY;
String consumersecret = Constants.CONSUMER_SECRET;
String accessToken = "";
String accessTokenSecret = "";
try {
OAuthConsumer consumer = new DefaultOAuthConsumer(consumerkey,
consumersecret);
consumer.setTokenWithSecret(requestToken, requestTokenSecret);
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback", "oob");
additionalParams.put("oauth_verifier", verifierCode);
consumer.setAdditionalParameters(additionalParams);
String signedURL = consumer.sign(ACCESS_TOKEN_URL);
URL url = new URL(signedURL);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-type", "application/xml");
urlConnection.setRequestProperty("Content-Length", "0");
String accesstokenresponse = "";
if (urlConnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
accesstokenresponse = sb.toString();
}
if (accesstokenresponse != null) {
String[] responseElements = accesstokenresponse.split("&");
if (responseElements.length > 1) {
accessToken = responseElements[1].split("=")[1];
accessTokenSecret = responseElements[0].split("=")[1];
Map<String, String> accesstokenmap = new HashMap<String, String>();
accesstokenmap.put("accessToken", accessToken);
accesstokenmap.put("accessTokenSecret", accessTokenSecret);
return accesstokenmap;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Constants Class
public class Constants {
public static final String APP_TOKEN = ""; // First three credentials are from **Production** part not from **Development** part
public static final String CONSUMER_KEY = "";
public static final String CONSUMER_SECRET = "";
public static final String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static final String AUTH_URL = "https://appcenter.intuit.com/Connect/Begin";
public static final String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static final String OAUTH_CALLBACK_SCHEME = "oauthflow-quickbooks";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
+ OAUTH_CALLBACK_HOST;
public static final String PREFERENCE_NAME = "quickbooks";
public static String OAUTH_URL = "https://oauth.intuit.com";
public static String APPCENTER_URL = "https://appcenter.intuit.com";
}
Manifest file
Add following intent filter to activity when login is initiated.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="oauthflow-quickbooks" />
</intent-filter>
I am working with Web application with C# where user will browse a video file and web application will upload to YouTube via YouTube API V3. I am getting the error. Please advice where i am doing wrong?
Error: System.ArgumentNullException: Value cannot be null. Parameter name: baseUri at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Upload.ResumableUpload1.d__e.MoveNext() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis\Apis[Media]\Upload\ResumableUpload.cs:line 459
I followed the below points.
Created ClientID for Webapplication and downloaded client_secrets.json file from API Access page.
Used the .Net sample code provided in https://developers.google.com/youtube/v3/docs/videos/insert#examples also referred same code from https://developers.google.com/youtube/v3/code_samples/dotnet
My application got authorized to YouTube API.
While uploading the video file, i am getting below error.
I am pasting below my code for your reference.
/* TestFileUploader.aspx */
<%# Page Language="C#" AutoEventWireup="true" CodeFile="TestFileUploader.aspx.cs" Inherits="TestFileUploader" Async="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form id="qaform" runat="server">
<div>
<p>
<asp:FileUpload runat="server" ID="FileUpload1" onchange="AddEventChoosePicture(this,'FileUpload1')"
Style="width: 100%;" />
</p>
<p>
<asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="Submit" />
</p>
</div>
</form>
</body>
</html>
/* TestFileUploader.aspx.cs */
using System;
using System.Web;
using System.IO;
using QA.credential;
using Google.Apis.Auth.OAuth2;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using Google.Apis.YouTube.v3.Data;
using Google.Apis.Upload;
public partial class TestFileUploader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submit_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
String FileUpload1_Ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
UploadVideos(FileUpload1.FileContent, FileUpload1.PostedFile.ContentType);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private async void UploadVideos(Stream uploadedStream, String contenttype)
{
try
{
UserCredential credential;
String clientsecretkeypath = HttpContext.Current.Server.MapPath("~/client_secrets.json");
using (var stream = new FileStream(clientsecretkeypath, FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeUpload },
"user", System.Threading.CancellationToken.None);
}
// Create the service.
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
//ApiKey = "AIzaSyAFxuAA4r4pf6VX75zEwCrIh5z4QkzOZ6M",
HttpClientInitializer = credential,
ApplicationName = PhotoandVideoupload.applicationname
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "My Test Movie";
video.Snippet.Description = "My description";
video.Snippet.Tags = new string[] { "Autos" };
video.Snippet.CategoryId = "2";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted";
// Using snippet,status below throws 401(UnAuthorized issue).
// Using snippet alone throws 404(Bad Request).
//In both case, Null Exception throws for parameter baseURI.
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
Google.Apis.Upload.IUploadProgress progress = await videosInsertRequest.UploadAsync();
switch (progress.Status)
{
case UploadStatus.Uploading:
Response.Write(String.Format("{0} bytes sent.", progress.BytesSent));
break;
case UploadStatus.Failed:
Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
break;
}
// Also tried to read file from server path instead of uploading via fileupload control.
/*
using (var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/1.mp4"), FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, contenttype);
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
*/
}
catch (Exception ex)
{
Response.Write(ex.Message + " " + ex.StackTrace);
}
finally
{
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Response.Write(String.Format("{0} bytes sent.", progress.BytesSent));
break;
case UploadStatus.Failed:
Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Response.Write(String.Format("Video id '{0}' was successfully uploaded.", video.Id));
}
}
Please advice where i am doing wrong?
Thanks,
You might try the following change:
From:
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);
To:
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", uploadedStream, contenttype);
Also, what is in contenttype? I use video/* as the contenttype for video uploads.
The status code 401 error may be because the YouTube API has not been authorized. Check that you have authorized the YouTube API for your credentials. Go to Google Developers Console and click on your project name. Then click on "APIs" in the left navigation menu. Check to see that YouTube Data API v3 is On.
I would like to ask if anyone can help me with an example to download a file using Struts 2 annotation
I have tried this in my action class
public class MyClass {
private InputStream fileInputStream;
private String fileName;
#Override
#Action(AbstractBasisAction.VIEW)
public String view() {
System.out.println("HoursCycleDownloadFrameAction: view");
super.view();
return SUCCESS;
}
public InputStream getFileInputStream() {
return fileInputStream;
}
#Action(value = "downloadFile", results = { #Result(name = "success", type = "stream", params = { "contentType", "application/octet-stream", "inputName", "fileInputStream", "contentDisposition", "filename=\"${fileName}\"", "bufferSize", "1024" }) })
public String downloadFile() throws Exception {
fileName = "license.txt";
fileInputStream = new FileInputStream(new File("C:\\", fileName));
return SUCCESS;
}
}
and this is what my page contains
<s:url id="fileInputStream" namespace="/myClass" action="downloadFile" ></s:url>
Download file - <s:a href="%{fileInputStream}">lisence.txt</s:a>
but the problem now is that it downloads the file with the action method name. Means that the file name is downloadFile.action. Can anyone help me with that?
1) if it is a .txt file, "contentType", "application/octet-stream"
should instead be "contentType", "plain/text";
2) you need a getter for your private String fileName; variable;
3) "contentDisposition", "filename=\"${fileName}\"" should contains extension, and eventually inline (default, open in browser) or attachment (ask if donwload or open with client application), for example
"contentDisposition", "attachment; filename=\"${fileName}.txt\""
public void consumeIt(){
HttpConnection con = null;
InputStream is = null;
try {
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
con = (HttpConnection) Connector.open(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = is.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
final String result = rawResponse.toString();
System.out.println("result:" + result);
}
catch (final Exception ex) {
System.out.println("error:" + ex.getMessage());
}
finally {
try {
is.close();
is = null;
con.close();
con = null;
}
catch(Exception e){}
}
}
I found the code above that is supposed to grab the xml data returned by the api, however I can't seem to get it working. The system print out with "poo" shows up, but not the "Works here." I have no idea what's wrong. I'm running it in a 9700 simulator.
Why is it so complicated to connect to a web service!
Please read about BB transports and networking.
For quick fix use this url:
"http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC;deviceside=true"
instead of yours.
I already answer this type of errors occurred because of Network extensions
just see this answer this and take changes in your code absolutely it will work
please check the following link and take directions
https://stackoverflow.com/a/8575601/914111
after importing two classes into your project just change your code as following way
public void consumeIt(){
HttpConnection con = null;
InputStream is = null;
try {
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
HttpConnectionFactory factory = new HttpConnectionFactory(0);
con = factory.getHttpConnection(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = is.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
final String result = rawResponse.toString();
System.out.println("result:" + result);
}
catch (final Exception ex) {
System.out.println("error:" + ex.getMessage());
}
finally {
try {
is.close();
is = null;
con.close();
con = null;
}
catch(Exception e){}
}
}
i got output as on my console like
result:<?xml version="1.0" encoding="UTF-8"?> <ResultSet version="1.0"><Error>0</Error><ErrorMessage>No error</ErrorMessage><Locale>us_US</Locale><Quality>87</Quality><Found>1</Found><Result><quality>85</quality><latitude>38.898717</latitude><longitude>-77.035974</longitude><offsetlat>38.898590</offsetlat><offsetlon>-77.035971</offsetlon><radius>500</radius><name></name><line1>1600 Pennsylvania Ave NW</line1><line2>Washington, DC 20006</line2><line3></line3><line4>United States</line4><house>1600</house><street>Pennsylvania Ave NW</street><xstreet></xstreet><unittype></unittype><unit></unit><postal>20006</postal><neighborhood></neighborhood><city>Washington</city><county>District of Columbia</county><state>District of Columbia</state><country>United States</country><countrycode>US</countrycode><statecode>DC</statecode><countycode>DC</countycode><uzip>20006</uzip><hash>B42121631CCA2B89</hash><woeid>12765843</woeid><woetype>11</woetype></Result></ResultSet> <!-- gws14.maps.sg1.yahoo.com uncompressed/chunked Thu Dec 22 21:22:38 PST 2011 --> <!-- wws2.geotech.sg1.yahoo.com uncompressed/chunked Thu Dec 22 21:22:38 PST 2011 -->
You can try this.
public void consumeIt()
{
HttpConnection con = null;
InputStream is = null;
String desiredEncoding = "ISO-8859-1";
StringBuffer returnStringBuffer = new StringBuffer();
OutputStream os=null;
try
{
String url = "http://where.yahooapis.com/geocode?q=1600+Pennsylvania+Avenue,+Washington,+DC";
System.out.println("poo" + url);
HttpConnectionFactory factory = new HttpConnectionFactory(0);
con = factory.getHttpConnection(url);
final int responseCode = con.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
System.out.println("response code:" + responseCode);
}
System.out.println("Works here");
is = con.openInputStream();
int ch;
String contenttype = httpConnection.getHeaderField("Content-Type");
if (contenttype != null)
{
contenttype = contenttype.toUpperCase();
if (contenttype.indexOf("UTF-8") != -1)
{
desiredEncoding = "UTF-8";
}
}
InputStreamReader isr = new InputStreamReader(inputStream,desiredEncoding);
while ((ch = isr.read()) != -1)
{
returnStringBuffer.append((char) ch);
}
result=returnStringBuffer.toString();
System.out.println("Result........"+result);
}
catch (final Exception ex)
{
System.out.println("error:" + ex.getMessage());
}
finally
{
try
{
is.close();
is = null;
con.close();
con = null;
}
}
}