Java - Put Request - java

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 ?

Related

Java HttpURLConnection invoke remote server and returned 500 status

I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)

How can I write an api post request from Java to c#

Recently I needed to move some code from Java to C#.
This is one of the methods that I couldn't rewrite... can someone help me?
public static String coreApiPostRequest(URL url, String input) {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
String responseMessage=null;
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
responseMessage = output;
}
conn.disconnect();
return responseMessage;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Android HttpURLConnection with json string

I want to call the following URL:
http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Use this address to add a new user to the database. To do this I use HttpURLConnection in my AsyncTask class
try {
URL myUrl = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("lab", "The response is: " + response);
statusMap.put("addUser", Integer.toString(response));
Log.d("lab", "URL: " + params[0]);
}catch (Exception e){
Log.d("lab", "Error2: " + e.getMessage());
}
params[0] = http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Unfortunately, this call is not working. I do not get the error.
catch returns null
Try like this way. You need to add few line in your code.
public JSONObject makeHttpRequest(String requestURL, JSONObject register) {
try {
url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(150000);
connection.setConnectTimeout(150000);
connection.setAllowUserInteraction(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setFixedLengthStreamingMode(register.toString().getBytes().length);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(register.toString());
outputStream.flush();
Log.e("URL", connection.getURL().toString());
Log.e("JSONObject", register.toString());
} catch (Exception e) {
Log.e("MAIN Exception", e.toString());
}
try {
int statuscode = connection.getResponseCode();
if (statuscode == HttpURLConnection.HTTP_OK) {
is = connection.getInputStream();
} else {
}
} catch (IOException e) {
Log.e("IOException", e.toString());
}
try {
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
Log.e("Response", response.toString() + " ");
rd.close();
} catch (IOException e) {
Log.e("BUFFER_READER", e.toString());
} catch (NullPointerException e) {
Log.e("NullPointerException", e.toString());
} finally {
connection.disconnect();
}
try {
return new JSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSONException", e.toString());
}
return null;
}
Also You are using localHost you must have emulator which can connect to localhost. Unless it will not going to work on any device.
try this :
private String post(String url) throws JSONException {
JSONObject json = new JSONObject();
try {
String query = "";
String EQ = ":";
String AMP = "&";
for (NameValuePair param : parameters) {
query = json.put(param.getName(), param.getValue()) + ",";
}
// url+= "?" + query;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if (parameters != null) {
StringEntity se = new StringEntity(query.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
Log.d("POSTQuery", url + parameters);
}
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.d("Status Code", "" + statusLine.getStatusCode());
if (statusLine.getStatusCode() == 200) {
return StringifyResponse(response);
}
Log.d("POSTQuery", url);
// Log.d("response", response.toString());
return StringifyResponse(response);
} catch (ClientProtocolException e) {
} catch (IOException e) {
Log.d("response", e.toString());
return "IOException";
}
return null;
}
You need to format all url querystring and then use outputwriter to flush the data :
// Create data variable for sent values to server
String data = URLEncoder.encode("syskey", "UTF-8")
+ "=" + URLEncoder.encode("1234", "UTF-8");
data += "&" + URLEncoder.encode("usrname", "UTF-8") + "="
+ URLEncoder.encode("256", "UTF-8");
data += "&" + URLEncoder.encode("usrpwd", "UTF-8")
+ "=" + URLEncoder.encode("556", "UTF-8");
and then flush the data:
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
Link here :
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89

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();
}

my android application get connection time out while the browser still can use

code:
public static String openUrl(String url, String method,
RequestParam params) throws NuageException {
HttpURLConnection conn = null;
String response = "";
String decodParam = params.decod();
if (method.equals(GET))
{
url = url + "?" + decodParam;
// Log.v(LOG_TAG, "GET:" + url);
}
try {
Log.v("开始请求:", String.valueOf(System.currentTimeMillis()));
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(READTIMEOUT);
conn.setConnectTimeout(CONNECTTIMEOUT);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
if (method.equals(POST)) {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(decodParam.getBytes("UTF-8"));
// Log.v(LOG_TAG, "POST:" + url + " " + decodParam);
}
InputStream is = null;
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200 || responseCode == 201
|| responseCode == 202) {
is = conn.getInputStream();
} else {
is = conn.getErrorStream();
}
response = read(is);
Log.v("请求结束:", String.valueOf(System.currentTimeMillis()));
Log.v(LOG_TAG, "response:" + response);
checkResponse(response);
} catch (MalformedURLException e) {
throw new NuageException(e);
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().equals(
"Received authentication challenge is null"))
throw new NuageException(new NuageError(
NuageError.ERROR_SESSIONKEY_INVALID, "", "", ""));
e.printStackTrace();
throw new NuageException(e);
} catch (NuageException e) {
throw e;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
sometimes i get java.net.SocketTimeoutException: Connection timed out while the browser still work.
anyone can help to improve my code?

Categories