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
}
Related
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?
I am doing something similar to mentioned in
Example of using StreamingOutput as Response entity in Jersey
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response streamExample(#Context UriInfo uriInfo) {
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException,WebApplicationException {
try{
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
//Read resource from jar
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("public/" + uriInfo.getPath());
...//manipulate the inputstream and build string with StringBuilder here//.......
String inputData = builder.toString();
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write(inputData);
writer.flush();
} catch (ExceptionE1) {
throw new WebApplicationException();
}
}
};
return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
}
I am trying to unit test this by mocking URIInfo like mentioned in How to get instance of javax.ws.rs.core.UriInfo
public void testStreamExample() throws IOException, URISyntaxException {
UriInfo mockUriInfo = mock(UriInfo.class);
Mockito.when(mockUriInfo.getPath()).thenReturn("unusal-path");
Response response = myresource.streamExample(mockUriInfo);}
I want to be able to check that I get an Exception when I switch the path to jar to something else.But, when I run/debug the test, I never enter the
public void write(OutputStream os) throws IOException,
WebApplicationException {...}
part and I only always hit the return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
Am I missing something very obvious here??
Because the stream is not written to until it hits the MessageBodyWriter (which is the component that ends up calling the StreamingOutput#write).
What you can do, is just get the Response from the return and call Response#getEntity() (which returns an Object) and cast it to StreamingOutput. Then call the write method yourself, passing an OutputStream, maybe a ByteArrayOutputStream so you can get the contents as a byte[] to check it. It all would look something like
UriInfo mockInfo = mockUriInfo();
Response response = resource.streamExample(mockInfo);
StreamingOutput output = (StreamingOutput) response.getEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
output.write(baos);
byte[] data = baos.toByteArray();
String s = new String(data, StandardCharsets.UTF_8);
assertThat(s, is("SomeCharacterData"));
I am using Jersey REST Webservices for my Application which is like a type of blog website ( means no user registration or authentication are required)
I have some webservices which queries the database and sends the data to the Front End .
As you know the user can see the webservice calls in browser network tab and fire the query manually
My question is , how can i protect sever / Service from being hit continously (for loop written manually to break the application)
This is how my service looks like
#GET
#Produces("text/plain")
public String displaylatestnews() {
String latestnews = "";
PreparedStatement selectpstmt = null;
ResultSet selectRset = null;
Connection conn = null;
String selectsql = "SELECT rssjson from rssfeeds limit 1";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
selectpstmt = conn.prepareStatement(selectsql);
selectRset = selectpstmt.executeQuery();
if (selectRset.next()) {
latestnews = selectRset.getString("rssjson");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
selectRset.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
selectpstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return "jsonCallback(" + latestnews.toString() + ")";
}
You can start avoiding creating a connection to mysql every time there's a request, secondly you can add some sort of caching to start with. Even a cache that only lasts few seconds can save tons of db accesses.
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've got this below restful webservice code. But when the webservice is accessed I'm getting "MIME media type application/pdf was not found". The docService.findByVersionId does return a "TestDoc" which holds the pdf content as byte[].
Can you please help me in fixing this problem?
#GET
#Path("/getPdf/{versionId}")
#Produces("application/pdf")
public Response getPdfFile(#PathParam("versionId") final String versionId) {
try {
final TestDoc doc = this.docService.findByVersionId(versionId);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(byteArrayOutputStream);
final byte[] pdfContent = doc.getPdfDoc();
bos.write(pdfContent);
bos.flush();
bos.close();
return Response.ok(byteArrayOutputStream).build();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
error:
Exception:
2014-01-02 12:42:07,497 ERROR [STDERR] 02-Jan-2014 12:42:07 com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.io.ByteArrayOutputStream, and Java type class java.io.ByteArrayOutputStream, and MIME media type application/pdf was not found
It seems that you can't use the ByteArrayOutputStream. The solution is to use StreamingOutput.
#GET
public Response generatePDF(String content) {
try {
ByteArrayOutputStream outputStream = service.generatePDF(content);
StreamingOutput streamingOutput = getStreamingOutput(outputStream);
Response.ResponseBuilder responseBuilder = Response.ok(streamingOutput, "application/pdf");
responseBuilder.header("Content-Disposition", "attachment; filename=Filename.pdf");
return responseBuilder.build();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
return Response.serverError().build();
}
}
private StreamingOutput getStreamingOutput(final ByteArrayOutputStream byteArrayOutputStream) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
byteArrayOutputStream.writeTo(output);
}
};
}