I am calling a url using this code
URL url = new URL(urlString);
HttpURLConnection httpCon = (HttpURLConnection) url
.openConnection();
httpCon.setRequestMethod("HEAD");
httpCon.setConnectTimeout(1200000);
httpCon.setReadTimeout(1200000);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Content-Type", "application/json");
int responseCode = httpCon.getResponseCode();
System.out.println(responseCode);
i am running a webservice in development server using local source code.the reponse is not coming back
note:-the service running time is 7-8 min.
Try this.
Imports are given below :
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.InputStream;
import java.io.InputStreamReader;
Code is given below :
URL url = new URL(urlString);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestMethod("HEAD");
httpCon.setConnectTimeout(1200000);
httpCon.setReadTimeout(1200000);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Content-Type", "application/json");
int responseCode = httpCon.getResponseCode();
System.out.println(responseCode);
//For getting the response in JSON
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) httpCon.getContent()));
JsonObject innerRootobj = root.getAsJsonObject();
System.out.println("innerRootobj : " + innerRootobj);
Related
I am sending JSON data to external API as following :
Dim url = "https://********"
Dim _httpClient = New HttpClient()
_httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("MyUsername", "MyPassword")
Using content = New StringContent(json, System.Text.Encoding.UTF8, "application/json")
Dim result As HttpResponseMessage = _httpClient.PostAsync(url, content).Result
If result.StatusCode = System.Net.HttpStatusCode.Created Then
Console.WriteLine(result.StatusCode)
Return True
End If
but I am receiving the following error:
{"status":400,"message":"Invalid Request","data":[{"field":"username","message":"Username required"},{"field":"password","message":"Password required"}]}
how to fix this issue ?
As per your API definition it is expecting username and password in the header as key value pair. you can add them like this.
_httpClient.DefaultRequestHeaders.Add("Username", "MyUsername");
_httpClient.DefaultRequestHeaders.Add("password", "MyPassword");
i need help with my WebAPI. I have the following in the server :
[System.Web.Http.HttpGet]
public HttpResponseMessage Recognize(byte[] img)
{
}
And my client requests :
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/MP.Business.Implementation.FaceAPI/");
using (var request = new HttpRequestMessage(HttpMethod.Get, client.BaseAddress))
{
var imageStream = new ByteArrayContent(pic);
var multi = new MultipartContent();
multi.Add(imageStream);
// var response = client.
HttpResponseMessage response = client.GetAsync("api/Recognition/Recognize/"+ multi).Result;
The breakpoint is not hit and i get 404.However if i send this request :
HttpResponseMessage response = client.GetAsync("api/Recognition/Recognize/").Result;
the breakpoint is hit and obviously i get error inside , because the byte[] is null(but at least it hits) . What do i do wrong ?
I want to convert a long URL into short one.
I have followed the documentation, but I'm not able to convert the URL.
It's resulting in 403 response.
I followed below aproach.
JSONObject reqObj = new JSONObject();
reqObj.put("longUrl", LONG_URL_TO_CONVERT);
reqObj.put("key", API_KEY);
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(reqObj.toString().getBytes());
InputStream inputStream = conn.getInputStream();
String resp = readStream(inputStream);
I tried with GET request
https://www.googleapis.com/urlshortener/v1/url?key=API_KEY&longUrl=www.google.com
but it's returning an error message Required parameter: shortUrl
What I'm doing wrong here ?
Finally found the solution.
Instead of adding key as a post param, appended it to the URL itself. like
https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}
and it worked as expected.
I am trying to write a http client which connects to a kerberos enabled tomcat(tested to be correct using browsers). It first gets the response code (which will be 401) and as according continue with its work.
The code is
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
public class SampleHTTP2 {
static final String kuser = "correctusername"; // your account name
static final String kpass = "correctpassword"; // your password for the account
static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
//System.out.println("I am reaching here");
// I haven't checked getRequestingScheme() here, since for NTLM
// and Negotiate, the username and password are all the same.
System.err.println("Feeding username and password for "
+ getRequestingScheme());
return (new PasswordAuthentication(kuser, kpass.toCharArray()));
}
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://mycompname:6008/examples/");
HttpURLConnection h1 = (HttpURLConnection) url.openConnection();
int rescode = h1.getResponseCode();
System.out.println(rescode);
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", "C:\\login2.conf");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
System.setProperty("java.security.krb5.conf", "C:\\krb5.ini");
if(rescode == 401){
Authenticator.setDefault(new MyAuthenticator());
URL url2 = new URL("http://mycompname/examples/");
URLConnection h2 = url2.openConnection();
InputStream ins2 = h2.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins2));
String str;
while((str = reader.readLine()) != null)
System.out.println(str);
}
}
}
Now when i comment the line:-
int rescode = h1.getResponseCode();
and put if(true) instead of if(rescode ==401), it works.
I am not sure what is going wrong. getResponseCode() internally calls getinputStream and thus I have used a separate url connection. Even still it does not work
P.S - Server is perfectly set up and the Authenticator class is also correct.
I am trying to hit .svc service from my JME application using POST method. but getting 'bad request'. Following is my code.
HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", ""+(postMsg.getBytes().length));
out = hc.openOutputStream();
out.write(postMsg.getBytes());
System.out.println("hc.getResponseCode() = "+hc.getResponseCode()+ " hc.getResponseMessage() = "+hc.getResponseMessage());
Please tell me what is wrong with the code.
Instead of http, I used Ksoap2-j2me-core jar with following code that i found -
SoapObject request = new SoapObject("namespace", "login");
request.addProperty("username", "pranav");
request.addProperty("password", "gangan");
//create the SOAP envelope
final SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.setOutputSoapObject(request);
//create the transport and then call
final HttpTransport httpTransport = new HttpTransport("http://URL");
httpTransport.call("\"login\"", env);
SoapObject body = (SoapObject) env.bodyIn;
//body.getProperty(0) will return the content of the first tag inside body
Object response = body.getProperty(0);
System.out.println(response.toString);