I am trying to POST JSON data to my WCF service but I get a Not Found error.
Code:
public void ReportSighting()
{
var uri = new Uri("http://demo.notifysolutions.com/MobileService.svc/ReportSighting", UriKind.Absolute);
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.Headers[HttpRequestHeader.ContentLength] = jsonData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.UploadStringAsync(uri, "POST", jsonData);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(ReportSightingCompleted);
System.Threading.Thread.Sleep(200);
}
private void PostCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Error:
InnerException = {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at Syst...
I have tried this in Fiddler and it works fine.
Related
I want to get the status code of each redirected URL (with URL). I know there is a way through which we can get all redirection URLs by passing HttpClientContext but I want a status code as well. Is there any way to get a status code as well along with url?
var httpget = new HttpGet("www.dummy-url.com");
try (final var closeableHttpResponse = closeableHttpClient().execute(httpget, context);) {
final var instream = closeableHttpResponse.getEntity().getContent();
instream.close();
List<URI> redirectURIs = context.getRedirectLocations();
EntityUtils.consumeQuietly(closeableHttpResponse.getEntity());
}
Use a custom response interceptor to capture all incoming response messages
CloseableHttpClient httpclient = HttpClients.custom()
.addInterceptorLast(new HttpResponseInterceptor() {
#Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpClientContext clientContext = HttpClientContext.adapt(context);
RouteInfo route = clientContext.getHttpRoute();
HttpRequest request = clientContext.getRequest();
HttpHost targetHost = route.getTargetHost();
try {
URI uri = new URIBuilder(request.getRequestLine().getUri())
.setScheme(targetHost.getSchemeName())
.setHost(targetHost.getHostName())
.setPort(targetHost.getPort())
.build();
System.out.println(uri + " -> " + response.getStatusLine());
} catch (URISyntaxException ex) {
// unexpected. do some recovery
}
}
})
.build();
try {
HttpGet httpget = new HttpGet("http://google.com/");
httpclient.execute(httpget, new ResponseHandler<Void>() {
#Override
public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return null;
}
});
System.out.println("----------------------------------------");
} finally {
httpclient.close();
}
http://google.com:80/ -> HTTP/1.1 301 Moved Permanently
http://www.google.com:80/ -> HTTP/1.1 200 OK
----------------------------------------
I have a jersey server. When I attempt to handle a POST from AngularJS (1.2.16), it is generating an error (below). When I use a java jersey client to post the message, the jersey server handles it fine.
SEVERE: null
java.lang.IllegalAccessException: Class com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator$8 can not access a member of class javax.ws.rs.core.Response with modifiers "protected"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:101)
at java.lang.Class.newInstance(Class.java:427)
this is the jersey post server:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/post")
public Response verifyAccount( Owner owner ,
#Context HttpServletRequest req)
{
LOGGER.debug("verify account " +owner.toString() );
HashMap<String, Object> results = new HashMap<String, Object>();
boolean verified = AccountManagement.verifyAccount(owner.getEmail(),
owner.getPwd());
if (verified) {
results.put("status", "OK");
} else {
results.put("status", "Fail");
}
return Response.status(200).entity(results)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
.build();
}
This is the jersey java client:
public class JsonClient {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://myserver.com:8080/restws/accountcheck/post");
String input = "{\"email\":\"fubar#gmail.com\",\"pwd\":\"hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
int code = response.getStatus();
if (code != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
System.out.println("exception caught.");
e.printStackTrace();
}
}
}
This is the AngularJS code to post:
$scope.ownerLoginAction = function() {
var dataObject = {
"email": $scope.myId,
"pwd": $scope.mypassword
};
var request = $http({
method: "post",
url: hostName+'/restws/accountcheck/post',
params: {
action:"verify"
},
data: dataObject
});
request.then (function(response) {
console.log(response.data);
},function(errResponse) {
console.error('Error');
} )
}
Anybody know why I cannot seem to post either with JSON from AngularJS? Is the server not set up right? Or the angularJS client is not right?
When i put a TCPMON in between, I noticed that the angularJS attempt sent an OPTION. Is that a clue that I dont understand?
So here is my code, its purpose is to fecth a json file. I get an error 500 from the server, which means I know that it is an internal server error. As I can't access to the logs of the the server, I'm pretty much stuck from now... I read about session and cookies, maybe that's it. What do you guy think of it ?
private class ListingFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "ListingFetcher";
public static final String SERVER_URL = "http://www.myurl.com/listing.json";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Listing> events = new ArrayList<Listing>();
events = Arrays.asList(gson.fromJson(reader, Listing[].class));
content.close();
handlePostsList(events);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
My code is perfectly working. THe only mistake is on this line :
HttpPost post = new HttpPost(SERVER_URL);
Which should be
HttpGet get = new HttpGet(SERVER_URL);
I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}
I tried to get and set Json but I have an exception on the "endgetresponse":
public void GetSetJsonString (string message)
{
this.message = message;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myurl);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = "POST";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(myurl, myfirstcookie);
request.CookieContainer.Add(myurl, mysecondcookie);
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(message);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string answer = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
}
}
On the line
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
I obtained this exception:
{System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClasse.b_d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c_DisplayClass1.b_0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at project.GetSetJson.GetResponseCallback(IAsyncResult asynchronousResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClass1d.b_1b(Object state2)}
Curiously, when the Json message that I send as a mistake, I didn't have the exception and I received an error message from the server.
Did you have an idea why I have this exception and how I can resolve this problem?
Tank you very much!