I am trying to get the response from webservice- http://services.groupkt.com/state/get/IND/all .It is working fine normally through java code but when I have deployed in google app engine it is returning 500 error.
Following one is the code.
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// Create new getRequest with below mentioned URL
HttpGet getRequest = new HttpGet("http://services.groupkt.com/state/get/IND/all");
// Add additional header to getRequest which accepts application/xml data
getRequest.addHeader("accept", "application/json");
// Execute your request and catch response
HttpResponse response = httpClient.execute(getRequest);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have searched it.It is showing as internal server error.How can i fix it?
Related
i have a GET method to connect to a webservices in xamarin. The method works fine, but when my phone is not connected to internet, the application crash, i would like to know how to avoid this ? Thanks for your answers:
static public string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
HttpWebRequest throws an Exception if there is no internet connection.
You have handled the Exception using the catch block but there, you have also written throw which throws the exception again and if you haven't handled it into the calling method, your app will crash.
Either try removing throw from your catch block, or handle Exception again into a calling method.
Like
try
{
var result = Get("myUrl");
}
Catch(Exception ex)
{
//Handle it here too
}
I need to download a image files from the file system using RESTEasy web service and the input httpclient is JSON and the output response is
#Produces({"image/jpeg,image/png"})
Here is my client code:
public void getFileDownload(){
log("inside getServerPath....");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(downloadWebService_URL);
JSONObject json = new JSONObject();
json.put("filePath", "/ngs/app/sample.png");
json.put("fileName", "sample.png");
log("json-->"+json.toString());
StringEntity inputJson = null;
try {
inputJson = new StringEntity(json.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
log("inputJson = " + inputJson.toString());
inputJson.setContentType("application/json");
httpPost.setEntity(inputJson);
httpPost.addHeader("AppType", "TC");
log("httpPost... httpPost");
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
log("response:-->"+response);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
log("E:: " + ExceptionUtils.getStackTrace(e));
}
}
Here is my Webservice code:
#Path("/downloadservice")
public class DownloadFileWS {
private static final String FILE_PATH = "/ngs/app/sample.png";
#POST
// #Path("/images")
#Path("/{fileName}/images")
#Consumes({"application/json"})
#Produces({"image/jpeg,image/png"})
public Response getImageFile(#PathParam("fileName") String fileName) {
File file = new File(FILE_PATH);
System.out.println("File requested is : " + fileName);
Logger.getLogger("!!!!!!!!!!!"+FILE_PATH);
System.out.println("########"+FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"sample.png\"");
return response.build();
}
The HTTP Response is:
response:-->HTTP/1.1 200 OK [Date: Tue, 19 Jul 2016 00:36:22 GMT,
Content-Length: 6192, Content-Type: image/png, Content-Disposition:
attachment; filename="sample.png", X-Powered-By: Servlet/2.5 JSP/2.1]
org.apache.http.conn.BasicManagedEntity#2ace1307
Question:
1. Based on the response, it looks like the service is sending the image in HTTPResponse object. May i know how to download the image received from HTTP Response?
2. The requirement is to click a link which calls the webservice by passing JSON as input request and the image should automatically download to the user's local machine browser.
I am trying to send an XML soap request to a dynamics nav web service. This is the XML from the WSDL. I have created a web access key and its the one in the key parameter of the XML.
<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
<s11:Body>
<ns1:Create xmlns:ns1='urn:microsoft-dynamics-schemas/page/customerws'>
<ns1:CustomerWS>
<ns1:Key>+gn8Nu4i7iW7D/g9vCaI8HZE5IEi1NBkTBqDp5QfXe4=</ns1:Key>
<ns1:Shipping_Advice></ns1:Shipping_Advice>
<ns1:Shipment_Method_Code></ns1:Shipment_Method_Code>
<ns1:Shipping_Agent_Code></ns1:Shipping_Agent_Code>
<ns1:Shipping_Agent_Service_Code></ns1:Shipping_Agent_Service_Code>
<ns1:Shipping_Time></ns1:Shipping_Time>
<ns1:Base_Calendar_Code></ns1:Base_Calendar_Code>
<ns1:Customized_Calendar></ns1:Customized_Calendar>
<ns1:Currency_Code></ns1:Currency_Code>
<ns1:Language_Code></ns1:Language_Code>
<ns1:VAT_Registration_No></ns1:VAT_Registration_No>
</ns1:CustomerWS>
</ns1:Create>
</s11:Body>
</s11:Envelope>
And this is the code that am using to send this request:
Console.WriteLine("We have started");
string pageName = "http://hrp-dmu.uganda.hrpsolutions.co.ug:9047/DynamicsNAV80/WS/Uganda%20Management%20Institute/Page/CustomerWS";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageName);
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
req.ProtocolVersion = new Version(1, 1);
req.Headers.Add("SOAPAction", #"urn:microsoftdynamicsschemas/page/customerws:Create");
Console.WriteLine("After preparing request object");
string xmlRequest = GetTextFromXMLFile("E:\\tst3.xml");
Console.WriteLine("xml request : "+xmlRequest);
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
req.ContentLength = reqBytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("GetRequestStreamException : " + ex.Message);
}
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
Console.WriteLine("GetResponseException : " + exc.Message);
}
string xmlResponse = null;
if (resp == null)
{
Console.WriteLine("Null response");
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine("The response");
Console.WriteLine(xmlResponse);
}
Console.ReadKey();
when using NavUserPassword Authentication you'll need a certificate.
See here on MSDN
Cheers!
I'm trying to post a json Object to a web api project from a windows phone app but I'm still getting 404 error. For the post method, I'm using that code:
Mail mailToCheck = new Mail();
try
{
mailToCheck.MailProfil = TxtBox_mail.Text.ToString();
string json = JsonConvert.SerializeObject(mailToCheck);
var httpClient = new System.Net.Http.HttpClient(new HttpClientHandler());
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri("http://uri/api/Profil/CheckMail"), new StringContent(json));
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.HResult.ToString());
}
The method CheckMail on my conctroller:
[HttpPost]
[Route("api/Profil/CheckMail")]
public IHttpActionResult CheckMail([FromBody]Mail MailProfil)
{
if (MailProfil.MailProfil != null)
{
try
{
bool exists = Librairie.Profils.mailExists(MailProfil.MailProfil);
return Ok(exists);
}
catch(Exception ex)
{
return InternalServerError(ex);
}
}
else
{
return BadRequest();
}
}
The Mail object is exactly the same in the app as in the web api project. Does someone can tell me what I'm doing wrong here ?
Check some samples of HttpClient.PostAsync() here: https://monkeyweekend.wordpress.com/2014/10/23/how-to-send-text-json-or-files-using-httpclient-postasync/
I have created a web service -
#Path("/info")
public class RestFulService {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getPlain()
{
return " Web Service created";
}
}
When I am accessing through localhost browser is rendering - "Web Service created".
But when I am trying to consume this web service through a different app I am getting 404 error code - "Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 404
at RestConsumer.main(RestConsumer.java:28)
"
Code inside RestConsumer.java -
public static void main(String[] args) {
try {
String uri = "http://localhost:8080/RestFul/rest/info";
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", MediaType.TEXT_PLAIN);
conn.connect();
if (conn.getResponseCode() != 200) {
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();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone suggest the required change.
It is a basic setting problem in Eclipse EE Refer to this Youtube link at 6:54
It gives a step by step guide to rectify the same. Hope this helpstutorial