HttpURLConnection header - java

I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code).
My questions are:
Some of my web service just request header info, for example, I just need to
put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server?
try {
String input = jsonString;
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("errorcode" + conn.getResponseCode());
if (conn.getResponseCode() != 200) {
JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String jsonText = read(br);
System.out.println("jsonText: " + jsonText);

Related

Http 401 error when posting to GoogleGroups API in Java?

The documentation on the Google API site does not include any complete working examples on using the groups api to access or modify a group, such as adding a member. There are snippets for different parts, but I am getting a 401 error when I put it all together and I have no idea if I am leaving out some key part.
I have tried putting the snippets I have found together into a working application, but am getting a 401 error.
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("<path to my json file I downloaded from the service accounts page>"))
.createScoped(Collections.singleton("https://www.googleapis.com/auth/admin.directory.group"));
URL url = new URL("https://www.googleapis.com/admin/directory/v1/groups/<identifier to the group, such as the group email address>/members");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
conn.setRequestProperty("Accept", "application/json");
StringBuffer jsonParamsBuffer = new StringBuffer();
jsonParamsBuffer .append("{")
.append("\"email\": \"")
.append("test-email#notarealdomain.fake")
.append("\", ")
.append("\"role\": \"")
.append("MEMBER")
.append("\"")
.append("}")
.append("]")
.append("}");
OutputStream os = conn.getOutputStream();
os.write(jsonParamsBuffer.toString().getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Response from Google Groups APi:");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
Server returned HTTP response code: 401 for URL: https://www.googleapis.com/admin/directory/v1/groups//members

I post a form to PHP in java, but no response in Ubuntu 18.10

As the title, I want to implement a Web server by Java, the only problem is that I need post a form to login.php and then get the response.
The following code is how I post the data to PHP.
URL url = new URL("http://127.0.0.1:6789" + req.uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Convert string to byte array, as it should be sent
// req.form is the form data to post to the login.php
byte[] postDataBytes = req.form.getBytes(StandardCharsets.UTF_8);
// set the form from request as the post data to PHP
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.getOutputStream().write(postDataBytes);
// get response
int code = conn.getResponseCode();
InputStream is;
if (code == 200) {
is = conn.getInputStream();
fillHeaders(Status._200_);
} else {
is = conn.getErrorStream();
fillHeaders(Status._404_);
}
// get response conetent length from login.php
int length = conn.getContentLength();
The content of login.php is very simple:
<?php
echo 'User name is:' . $_POST['loginName'];
?>
When I debug this part, I will stall in this line
int code = conn.getResponseCode();
That means I cannot get response from login.php
So how can I change the code or the enviornment of ubuntu (maybe the version of php?) to solve this problem.
Thx. XD
If java is the server and PHP is a client you should open listening connection in java.
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line); line = reader.readLine();
}
}

get JSON response while performing POST request with HttpURLConnection

I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.
I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.
String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Setting the Request Method header as POST
con.setRequestMethod("POST");
//Prepairing credentials
String cred= "user123:p#ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);
//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);
//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");
//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");
con.setDoOutput(true);
JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());
os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();
Get the input stream and read it.
String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}

Response codes from Java.net.Url conection - Rest Webservice Client

I am using Java.Net.URL for making a Rest webservice call.
using the below example code.
URL url = new URL("UrlToConnect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
i am trying to capture response code from this webservice call. I observed that Even after putting a wrong URL i am getting 200 response code from the connection. Please suggest a way by which i can capture response codes 200 , 201 and 202.
Thanks.

Intercepting json in https(not http) with a python cgi script

I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
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);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?

Categories

Resources