I have documentation of server API with several methods. The problem is that I have never used API to work with server. What I can do to do it more easy?
Part of API documentation:
Method "Login":
POST http://api.example.com/login-ajax
Parameters:
email
password
Response:
{
"success":true,
"currentUser":222,
"userData":{
"displayName":"User",
"displayAvatarId":"asjhdsasduh",
"email":"qwerty#gmail.com",
"isEmailConfirmed":"0",
"sex":"m"
}
}
The response is JSON object, but I don't know how to send request to get this response.
Help me please.
UPGRADE
I tried to use Jsoup:
Connection.Response res = Jsoup.connect("http://api.example.com/login-ajax")
.data("email", "mail#gmail.com", "password", "pass")
.method(Connection.Method.POST)
.header("Accept", "application/json")
.header("X-Requested-With", "XMLHttpRequest")
.header("X-App-Api", "1.0")
.header("X-App", "iOS")
.ignoreContentType(true)
.execute();
Document document = Jsoup.parse(res.parse().outerHtml());
System.out.println(document.text());
The response is:
{"success":false,"exception":"Exception_User","message":"\u041c\u044b \u043d\u0435 \u043d\u0430\u0448\u043b\u0438 \u0432 \u0431\u0430\u0437\u0435 \u0442\u0430\u043a\u043e\u0435 \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0435 \u044d\u043b. \u043f\u043e\u0447\u0442\u044b \u0438 \u043f\u0430\u0440\u043e\u043b\u044f. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."}
UPGRADE 2
I also tried to use this one:
System.out.println(getJSON("http://api.example.com/login-ajax"));
public static String getJSON(String url) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("email", "mail#gmail.com");
c.setRequestProperty("password", "pass");
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("X-Requested-With", "XMLHttpRequest");
c.setRequestProperty("X-App-Api", "1.0");
c.setRequestProperty("X-App", "iOS");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(1000);
c.setReadTimeout(1000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
System.out.println("200");
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
case 201:
System.out.println("201");
br = new BufferedReader(new InputStreamReader(c.getInputStream()));
sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
System.out.println("MalformedURLException");
} catch (IOException ex) {
System.out.println("IOException");
}
return null;
}
And the response is:
{"success":false,"exception":"Exception_Validation","message":"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 e-mail","errors":{"email":["\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 e-mail."],"password":["\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u0430\u0440\u043e\u043b\u044c"]}}
As I haven't used Jsoup so far I can't give detailed information on how to use it, but I had to work with Restlet and therefore created my own JSON messages (either via org.json.JSONObject or via plain String). A post-example using Restlet would look something like this:
try
{
// create a Restlet client
ClientResource cr = new ClienResource("http://api.example.com/login-ajax");
// create the JSON message
JSONObject message = new JSONObject();
message.put("email", "mail#gmail.com");
message.put("password", "pass");
// use HTTP POST method to send the JSON message
cr.post(message, MediaType.APPLICATION_JSON);
// receive the answer - error checks omitted!
Response response = cr.getResponse();
JsonRepresentation jsonRep = new JsonRepresentation(response.getEntity());
// process the JSON response
JSONObject json = jsonRep.getJsonObject();
System.out.println("success: "+json.get("success"));
System.out.println("current user: "+json.get("currentUser"));
// extract the user data
JSONObject userData = (JSONObject)json.get("userData");
System.out.println("display name: "+userData.get("displayName"));
System.out.println("display avatar Id: "+userData.get("displayAvatarId"));
System.out.println("email: "+userData.get("email"));
System.out.println("is email confirmed: "+userData.get("isEmailConfirmed"));
System.out.println("sex: "+userData.get("sex"));
}
catch (ResourceException | JSONException ex)
{
ex.printStackTrace();
}
HTH
Consider to use an Apache HTTP Client to create a connection to your HTTP server.
Its a general-purpose library for working with HTTP requests. There are plenty resources that illustrate the usage of HTTP client, Here is an example
I admit, I've never used JSoup so I can't really comment on your example.
Hope this helps,
Mark
Related
This is the method I have written which sends a POST request to send an Email.
I am able to send the email and get the Response Code 200 Ok.
But I don't know how to get the JSON Response and convert it into an Object.
Can someone please tell me how to do this?
public void sendEmail() {
try {
URL url = new URL("https://mandrillapp.com/api/1.0/messages/send");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String data =
"{\"key\": \"" + mailchimpApiKey + "\", " +
"\"message\": {" +
"\"from_email\": \"from#gmail.com\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"to#gmail.com\", \"type\": \"to\" }]}}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(out);
System.out.println(httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
A basic search reveals: https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.
In addition to the answer by #mdre
I use the org.json library to convert responses into JSON Objects. The following method does exactly this:
import org.json.JSONException;
import org.json.JSONObject;
public static JSONObject convertResponseToJSONObject(String responseString) {
try {
JSONObject jsonObj = new JSONObject(responseString);
return jsonObj;
} catch (JSONException e) {
System.err.println(
"It is not possible to create a JSONObject from the input string, returning null. Exception:");
e.printStackTrace();
}
return null;
}
Note that the response only represents a JSON object if it starts with a {. If it starts with a [ the response represents a JSON array.
You can get errorStream or inputStream based on the response code you receive and get the response from it. Below example creates a BufferedReader from the stream
BufferedReader br = null;
if (100 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
}
You can then read from the br and store data based on your requirement. Below will store data into StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
Instead of printing as String you can also convert it into JSON by using JSON libraries. You may follow this guide
I'm having issues trying to send over a JSON string to a REST API. Long story short, I'm taking user input in a form, sending it over to a java servlet to validate and work with it a bit, and then trying to send it to an endpoint.
I have the following method being called on in my doPost method in my servlet, I am using printwriter pw to be able to read back data being returned in my response in the browser console at this point.
String jsonData = //JSON STRING HERE\\
String username = //USERNAME\\
String password = //PASSWORD\\
String endpointURL = //ENDPOINT URL HERE\\
pw.println(sendJson(jsonData, username, password));
private String sendJSON(String jsonData, String usrname, String usrpass) {
try {
String auth = usrname + ":" + usrpass;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
URL url = new URL(endpointURL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(5000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json; utf-8");
http.setRequestProperty("Authorization", authHeaderValue);
http.setDoOutput(true);
//POST Json to URL using HttpURLConnection
//try(OutputStream os = http.getOutputStream()) {
OutputStream os = http.getOutputStream();
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
//}
/*String responseBody;
try(BufferedReader br = new BufferedReader(
new InputStreamReader(http.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//System.out.println(response.toString());
responseBody = response.toString();
return responseBody;
}
return responseBody;*/
BufferedReader in = new BufferedReader(
new InputStreamReader(http.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
return e.toString();
}
}
}
I was having issues with the try's so I rewrote it to try and just get functionality right away first. Right now I'm receiving "java.io.IOException: Server Returned HTTP response code: 500 for URL: //URL HERE\"
Would anybody have any tips to point me in the right direction? I feel like I'm just missing like a small piece of the puzzle at this point, and I'm having a hard time finding any tutorials showing what it is that I'm trying to do. Thank you so much to anyone for any tips/pointers!
Made sure I was able to authenticate and that wasn't the issue by just connecting and returning:
int statusCode = http.getResponseCode();
String statusCodeString = Integer.toString(statusCode);
return statusCodeString;
This worked fine, received 403 response when setting wrong password/username and 400 response when I change to correct.
I attempted using HttpClient as well instead, but was having issues trying to get that to work at all. I also had an error earlier with week trying to do this with a certificate error, but after reimporting the cert to my cacerts file this was resolved (unrelated to this issue I believe).
I'm trying to get my user information from stackoverflow api using a simple HTTP request with GET method in Java.
This code I had used before to get another HTTP data using GET method without problems:
URL obj;
StringBuffer response = new StringBuffer();
String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in this case I'm getting just stranger symbols when I print the response var, like this:
�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���#�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����
thanks in advance.
The content is likely GZIP encoded/compressed. The following is a general snippet that I use in all of my Java-based client applications that utilize HTTP, which is intended to deal with this exact problem:
// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection
// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
// Format is GZIP
// Replace inputSteam with a GZIP wrapped stream
inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text
BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...
This relies on the following imports: java.util.zip.GZIPInputStream; java.util.zip.Inflater; and java.util.zip.InflaterInputStream.
I am completely new to Android programming. I have come across the following problem -
I want to validate the credentials of the user who uses the application. For this I want to use POST method to send the Login details to the server. From there I want to get response in JSON format. I don't know how to receive the response. I am using Java for server side programming.
P.S. I would deal with security concerns bit later.
Following is my Android code. I know it is a mess.. Please help.
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("address");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
return -1;
}
There's an open source class you can use for just this, and you can easily browse the code to see how it works. There are actually many open source libs that do this, but the following is among the cleanest and easiest to work with in my opinion.
https://github.com/kevinsawicki/http-request/blob/master/lib/src/main/java/com/github/kevinsawicki/http/HttpRequest.java
And your code will probably look something like this:
Map<String, String> params = new HashMap<String, String>();
params.put("username", mUsername);
params.put("password", mPassword);
String response = HttpRequest.post(url).form(params).body();
EDIT
My original answer including the params map in to post method would have sent the request as a POST but the params in the url. The corrected version (form method) sends the params in the body.
You can convert your json response to a JSONObject class.
Look this app, the code is very simple.
#Override
public List<User> getRanking() {
final List<User> result = new ArrayList<User>();
String url = "http://quiz-exmo.rhcloud.com/rest/user/ranking/";
String json = HttpUtil.doGet(url);
try {
final JSONObject resultJsonObject = new JSONObject(json);
final JSONArray jsonArray = resultJsonObject.getJSONArray("users");
for (int index = 0, total = jsonArray.length(); index < total; index++) {
final JSONObject jsonObject = jsonArray.getJSONObject(index);
final User user = new User();
user.name = jsonObject.getString("name");
user.email = jsonObject.getString("email");
user.score = jsonObject.getInt("points");
result.add(user);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return result;
}
https://github.com/exmo/equizmo-android/blob/master/maven/equizmo/src/main/java/br/gov/serpro/quiz/service/rest/UserServiceRest.java
I want to send some information from PHP to Java. Why? Because I have a database on my server, and I get information from my database using PHP scripts.
Now I want to send that information to my client in Java. How can I do that?
I send information from Java to PHP by POST, and it works well, but I don't know how can I do the reverse.
Can you help me?
I saw this code, from a GET connection in Java... is it correct?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: I'm an android developer, not a Java developer...
From exampledepot: Sending POST request (Modified to get the output of your send.php.)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
P.S. This should work fine on Android. :)
(I usually import static java.net.URLEncoder.encode but that's a matter of taste.)