Posting a Json Object to Restful Web Service - java

I have to post the comment of a user to a web service. However I fail.
I have a AsyncTask class in which I do the following :
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsobj = null;
HttpURLConnection conn = null;
String urlStr = params[0];
String message = params[2];
String name = params[1];
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
jsobj.put("name", name);
jsobj.put("text", message);
jsobj.put("id", news_id);
DataOutputStream writer
= new DataOutputStream(conn.getOutputStream());
writer.writeBytes(jsobj.toString());
writer.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsobj;
}
In initialization I do the following:
DataTask4 tsk = new DataTask4();
tsk.execute("http://94.138.207.51:8080/NewsApp/service/news/savecomment",commentowner,message)
I don't know what I am doing wrong but seems that I can put the json object correctly to the web-service.

Related

Aplication with json-simple crash after non json data

Ive got
HttpURLConnection urlConnection = null;
String result = "";
try {
String host = "http://www.example.com/json.json";
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
} else { result="9";}
return result;
} catch (MalformedURLException e) {
result="9";
} catch (IOException e) {
result="9";
}
catch (ParseException e) {
e.printStackTrace();
result="9";
}
finally {
urlConnection.disconnect();
}
return result;
When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject
I think that
catch (ParseException e) {
e.printStackTrace();
result="9";
}
should handle this, but no.
So what i must do to avoid situation that aplication will crash when i do not get valid json?
The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?
catch (ClassCastException e) {
e.printStackTrace();
result="9";
}
Try this to make a http request
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
URL myUrl = null;
HttpURLConnection conn = null;
String response = "";
//String data = params[0];
try {
myUrl = new URL("http://www.example.com/json.json");
conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//one long string, first encode is the key to get the data on your web
//page, second encode is the value, keep concatenating key and value.
//theres another ways which easier then this long string in case you are
//posting a lot of info, look it up.
String postData = URLEncoder.encode("key", "UTF-8") + "=" +
URLEncoder.encode("value", "UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
} catch (JSONException e) {
//s may not be json
}
}
}
Before getting String from Json Object, check whether the Json object is not null and has that string. and then try to get it.
if (jsonObject!=null && jsonObject.has("name"))
{
result = jsonObject.get("name");
System.out.print(result);
}

android Error converting result java.io.FileNotFoundException

I have created an API in post method which is working fine in postman i.e it is giving desired response. But while using that API in Android it is giving error:
Error converting result java.io.FileNotFoundException and Error parsing data org.json.JSONException: End of input at character 0 of
I would appreciate anyone guiding me on how to do this.
Here is the code of makeHttpRequest method of jsonparser:
public JSONObject makeHttpRequest2(String url2 , String method,
String name, String password) throws IOException {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
url = new URL(url2);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Host", "android.schoolportal.gr");
conn.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", name);
//jsonParam.put("email", email);
jsonParam.put("password", password);
Log.d("json",String.valueOf(jsonParam));
OutputStreamWriter out=new OutputStreamWriter(
conn.getOutputStream());
out.write(jsonParam.toString());
out.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
try {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.d("json3",String.valueOf(json));
// return JSON String
return jObj;
}
First off you are not checking that the request was successful, before calling the conn.getInputStream(); If the request failed that stream is empty and you need to call
new BufferedReader(new InputStreamReader(connection.getErrorStream()));
What line number is giving you issue? If you print out the JSON to insure that the response is valid JSON.
Add this to your code:
conn.setDoInput(true); //After or before of setDoOutput(true) for organization :)
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
EDIT :
And this if you need to upload a JSON for the server:
conn.setRequestProperty("Content-Length", "" + Integer.toString(JsonObjectstr.getBytes().length)); // Get the json string length

Java - Put Request

I'm trying to perform a "PUT" but nothing happens, i don't catch any exception either.
Here is what I've tried:
String destinationUrl = 'http://stash.myDomain.com/rest/api/1.0/projects/myProj/permissions/users?name=myUser&permission=PROJECT_WRITE';
URL url = null;
try {
url = new URL(destinationUrl)
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
String userpass = STASH_USERNAME + ":" + STASH_PASSWORD;
String basicAuth = "Basic " + converter.printBase64Binary(userpass.getBytes());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", basicAuth)
//httpURLConnection.setRequestProperty("Content-Type", "application/json");
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes("Hello");
} catch (IOException excepption) {
excepption.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Any idea what should i do ?

Send PUT, DELETE HTTP request in HttpURLConnection

I have created web service call using java below code. Now I need to make delete and put operations to be perform.
URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();
When I add below code to perform DELETE action it gives errors saying:
java.net.ProtocolException: HTTP method DELETE doesn't support output.
conn.setRequestMethod( "DELETE" );
So how to perform delete and put requests?
PUT example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
DELETE example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
FOR PUT
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
FOR DELETE
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
Actually got it from the link here:
Send PUT, DELETE HTTP request in HttpURLConnection
i suggest you to use restlet client for web service request .please refer the bellow sample code ,it may help you
Client client = new Client(new Context(), Protocol.HTTP);
clientResource = new ClientResource(url);
ResponseRepresentation responseRep = null;
try {
clientResource.setNext(client);
clientResource.delete();
} catch (Exception e) {
e.printStackTrace();
}

Can't connect to Bitcoin wallet with JSON-RPC

I'm trying to connect to Bitcoin wallet from Java. But i get network exception: Server redirected too many times. I would be very glad if someone helps me understand.
Here's my code:
public static void SetupRPC() {
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("admin", "admin".toCharArray());
}
});
URL serverURL = null;
try {
serverURL = new URL("http://127.0.0.1:44843");
} catch (MalformedURLException e) {
System.err.println(e.getMessage());
}
JSONRPC2Session mySession = new JSONRPC2Session(serverURL);
String method = "getinfo";
int requestID = 0;
JSONRPC2Request request = new JSONRPC2Request(method, requestID);
// Send request
JSONRPC2Response response = null;
try {
response = mySession.send(request);
} catch (JSONRPC2SessionException e) {
System.err.println(e.getMessage());
}
if (response.indicatesSuccess())
System.out.println(response.getResult());
else
System.out.println(response.getError().getMessage());
}
And .conf file:
rpcuser="admin"
rpcpassword="admin"
rpcallowip=*
rpcport=44843
server=1
daemon=1
listen=1
rpcconnect=127.0.0.1
If these are your code and .conf, then remove the " in your conf file. Or add \" to your string.
So this
return new PasswordAuthentication ("\"admin\"", "\"admin\"".toCharArray());
or this
rpcuser="admin"
rpcpassword="admin"
Also you cannot have # in your password or username(which was my case).
After I found this I got an Invalid JSON-RPC 2.0 response.
My solution was to change !jsonObject.containsKey("error") to (!jsonObject.containsKey("error") || jsonObject.get("error") == null) in the function
public JSONRPC2Response parseJSONRPC2Response(final String jsonString) which is located in the base of JSONRPC 2.0 in JSONRPC2Parser.java somewhere around line 495.
EDIT: This was on the DogeCoin-QT, so maybe the Bitcoin-QT does not have this problem.
Ok, i solve this problem:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
});
String uri = "http://127.0.0.1:8332";
String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"getbalance\"}";
String contentType = "application/json";
HttpURLConnection connection = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length));
connection.setUseCaches(true);
connection.setDoInput(true);
OutputStream out = connection.getOutputStream();
out.write(requestBody.getBytes());
out.flush();
out.close();
} catch (IOException ioE) {
connection.disconnect();
ioE.printStackTrace();
}
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response);
} else {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}

Categories