I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).
In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP script:
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
String urlString = "phpfilelocation.php" + "?" + data;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.connect();
//remove:
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP :
mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");
JAVA :
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");
Related
I'm trying to use Microsoft Graph to make a file search. I use this entry point : https://graph.microsoft.com/beta/search/query
My application do not use a user account but a daemon with an application key (see auth method).
And i send a built object.
My java code is rather simple :
public static void main(String[] args) throws Exception{
try {
// Authentication result containing token
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
String token = result.accessToken();
SearchDocumentResponseModel documentQuery = fileGraphs.searchDocument(token, QUERYSTRING, 0, 25);
System.out.println("Find a document" + documentQuery.toString());
} catch(Exception ex){
throw ex;
}
}
private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
CONFIDENTIAL_CLIENT_ID,
ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
.authority(TENANT_SPECIFIC_AUTHORITY)
.build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(GRAPH_DEFAULT_SCOPE))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
The SearchDocumentResponseModel is just a set of POJO that build for me the object that i must send as a request body.
{
"requests":
[{
"entityTypes":["microsoft.graph.driveItem"],
"query":{"query_string":{"query":"any query"}},
"from":0,"size":25
}]
}
The method searchDocument is just here to build the object before i send it to the API
public SearchDocumentResponseModel searchDocument(String accessToken, String stringSearch, int from, int size) throws IOException {
SearchDocumentRequestModel searchRequest = new SearchDocumentRequestModel();
// set values here
...
URL url = new URL("https://graph.microsoft.com/beta/search/query");
return requestsBuilder.buildPostRequest(accessToken, searchRequest, url)
}
Now i want to send to server the Json and expect an answer :
public SearchDocumentResponseModel buildPostRequest(String accessToken, SearchDocumentRequestModel searchRequest, URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// write the input json in a string
String jsonInputString = new Gson().toJson(searchRequest);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
String httpResponseMessage = conn.getResponseMessage();
// reading the response
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String outputResponse = response.toString();
return new Gson().fromJson(outputResponse, SearchDocumentResponseModel.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I think i set the properties correctly. Is it coming from my code or from Microsoft Graph ? Thanks !
First of all, you should check if the access token is valid, you can send a request using postman.
If the token is valid, I think it should be the problem of your jsonInputString. The following code works fine.
URL url = new URL("https://graph.microsoft.com/beta/search/query");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "access_token" );
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String str = "";
str += "{";
str += " \"requests\": [";
str += " {";
str += " \"entityTypes\": [";
str += " \"microsoft.graph.driveItem\"";
str += " ],";
str += " \"query\": {";
str += " \"query_string\": {";
str += " \"query\": \"contoso\"";
str += " }";
str += " },";
str += " \"from\": 0,";
str += " \"size\": 25";
str += " }";
str += " ]";
str += "}";
OutputStream os = conn.getOutputStream();
byte[] input = str.getBytes("UTF-8");
os.write(input, 0, input.length);
System.out.println(conn.getResponseCode());
Update:
Query api doesn't support client credential flow.
I have a json file which contains only objects now i cant able to fetch all the object with iteration as here is no array.
Here is the code : That i have tried in my android studio & JSon Data Screenshot
#Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://api.myjson.com/bins/r7dj6");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line =" ";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
String fullfile = stringBuffer.toString();
JSONObject jsonObject = new JSONObject(fullfile);
JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is a complete example. Works for me.
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.myjson.com/bins/r7dj6");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuffer = new StringBuilder();
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
Iterator<String> keys = apartmentObject.keys();
while (keys.hasNext()) {
String flatName = keys.next();
JSONObject flat = apartmentObject.getJSONObject(flatName);
String age = flat.getString("age");
String color = flat.getString("color");
String name = flat.getString("name");
String owner = flat.getString("owner");
String partner = flat.getString("partner");
Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
You can still iterate:
for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
JSONObject flatName = json.get(key.next());
...
}
I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.
I've a return 0 from web services using postman if the data send successfully.
but I'm quite confused how to detect 0 message in android using HttpURLConnection
in HttpClient I'm using String response = httpclient.execute(httppost, responseHandler);
String response = httpclient.execute(httppost, responseHandler);
Log.d("MainActivity", "INSERT:" + response);
but refer to the docs
there's some code like getResponseCode() getResponseMessage() but the output is 200 for getResponseCode() and OK for getResponseMessage()
so how to get output of 0 in HttpURLConnection?
EDIT urlconnection code:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
int respon = conn.getResponseCode();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("Input", String.valueOf(conn.getInputStream()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
This is how you need to read the data from the server using HttpUrlConnection:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
InputStream is = null;
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = conn.getInputStream();// is is inputstream
} else {
is = conn.getErrorStream();
}
try {
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();
String response = sb.toString();
//HERE YOU HAVE THE VALUE FROM THE SERVER
Log.d("Your Data", response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
I need to submit my registration form details to server api. I have tried one method by calling a function on button click.But nothing is geting posted in the server and I am also not getting any exception.Please help me.
Thanks in advance.
Below is the code .
I have called the function like this
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
ex.printStackTrace();;
Toast.makeText(getActivity(),"URL Exception", Toast.LENGTH_LONG).show();
}
And below given is the function
public String GetText() throws UnsupportedEncodingException
{
HttpURLConnection connection = null;
// Get user defined values
Name = full_name.getText().toString();
Phonenumber = phone.getText().toString();
Email=email.getText().toString();
Password=password.getText().toString();
House = house.getText().toString();
Street = street.getText().toString();
Landmark = landmark.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(Password, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8")
+ "=" + URLEncoder.encode(Phonenumber, "UTF-8");
data += "&" + URLEncoder.encode("house", "UTF-8")
+ "=" + URLEncoder.encode(House, "UTF-8");
data += "&" + URLEncoder.encode("street", "UTF-8")
+ "=" + URLEncoder.encode(Street, "UTF-8");
data += "&" + URLEncoder.encode("areaname", "UTF-8")
+ "=" + URLEncoder.encode(Area, "UTF-8");
data += "&" + URLEncoder.encode("landmark", "UTF-8")
+ "=" + URLEncoder.encode(Landmark, "UTF-8");
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://application.easypani.com/app/customer/register");
// Send POST data request
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(data.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(data);
wr.flush();
wr.close();
// Get the server 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);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
Use this instead
private class PostData extends AsyncTask < String, Void, Void > {
protected Void doInBackground(String...params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://application.easypani.com/app/customer/register");
try {
// Add your data
String Name = params[0];
String Phonenumber = params[1];
String Email = params[2];
String Password = params[3];
String House = params[4];
String Street = params[5];
String Landmark = params[6];
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
nameValuePairs.add(new BasicNameValuePair("name", Name));
nameValuePairs.add(new BasicNameValuePair("email", Email));............................................................
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
}
And you use it like this
new PostData().execute(Name, PhoneNumber..and so on);