How can I call HTTP POST request with multiple parameters? - java

how can i call http post requst with multiple parameter.
like this
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
webClient.UploadStringAsync(new Uri(URL), "POST", JSON);
this one in c#. but i want in android
i have already try this
public String postServiceCall(String paraURL,JSONArray jsonParams, String usrId, String syncDt){
TAG = "makeHttpRequestJSONObject";
Log.d(MODULE, TAG + " called");
String json = "";
InputStream is = null;
try{
HttpParams httpParams = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
String params = "UserId="+ usrId +"&SyncDate="+syncDt;
String encodedUrl = URLEncoder.encode (params,"UTF-8");
HttpPost httpPost = new HttpPost(paraURL+encodedUrl);
httpPost.setHeader( "Content-Type", "application/json" );
Log.v(MODULE, TAG + ", POST paraURL " + (paraURL+encodedUrl));
Log.v(MODULE, TAG + ", POST paraURL jsonParams.toString() " + (jsonParams.toString()));
httpPost.setEntity(new ByteArrayEntity(jsonParams.toString().getBytes("UTF8")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString().trim();
json = json.substring(1,3);
Log.v(MODULE, TAG + ", json data " + json);
} catch (Exception e){
Log.e(MODULE, TAG + "Exception Occurs " + e);
json = "";
}
return json;
}
}
this code not work properly. this code post only the json. here userid and syncdate not send to server side

please check this
String encodedUrl = URLEncoder.encode (params,"UTF-8");
example
your code returns the url like this
input "http://test.com/ttttt?query=jjjj test"
output "http://test.com/ttttt?query=jjjj+test"
but your need url like this
output "http://test.com/ttttt?query=jjjj%20test"
so you can try this function for url encoding
public String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
OR
This may help you to comfortable with higher versions
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}

Related

Getting response code 400 when trying to get access token from Azure AD

I am implementing azure for my web application and trying to get access token by following there openId connect tutorial
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
And when i am requesting to get the access token, i am always getting bad request 400
Request to get access token :
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPl.......
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
here is my code :
public static String post( String endpoint,
Map<String, String> params) {//YD
StringBuffer paramString = new StringBuffer("");
//if(!Utilities.checkInternetConnection(context)){
// return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
//}
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
StringBuffer tempBuffer = new StringBuffer("");
String paramval;
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
if (param != null) {
if (paramString.length() > 0) {
paramString.append("&");
}
System.out.println( "post key : " + param.getKey());
String value;
try {
paramval = param.getValue();
if(paramval!=null)
value = URLEncoder.encode(paramval, "UTF-8");
else
value = "";
} catch (UnsupportedEncodingException e) {
value = "";
e.printStackTrace();
}
paramString.append(param.getKey()).append("=")
.append(value);
}
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(endpoint);
String data = "";
try {
// Add your data
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
//httppost.addHeader("Host", host);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
if (!paramString.equals("")) {
if (tempBuffer.length() > 0) {
data = data + tempBuffer.toString();
}
data = data + paramString.toString();
if (data.endsWith("&")) {
data = data.substring(0, data.length() - 1);
}
httppost.setEntity(new ByteArrayEntity(data.getBytes()));
}
System.out.println( "post Stringbuffer : " + data);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int statuscode = response.getStatusLine().getStatusCode();
System.out.println("Response code : " + statuscode);
if (statuscode != 200) {
return null;
}
HttpEntity entity = response.getEntity();
InputStream in = null;
if (entity != null) {
in = entity.getContent();
}
if (in != null) {
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
String response2 = builder.toString();
System.out.println("response :" + response2);
retrycount = 0;
return response2;
}
}
catch(UnknownHostException e){
e.printStackTrace();
return null;
}
catch (EOFException eof) {
if (retrycount < max_retry) {
eof.printStackTrace();
post( endpoint, params);
retrycount = 1;
}
} catch (Throwable th) {
throw new IOException("Error in posting :" + th.getMessage());
}
retrycount = 0;
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please help me with this
Thanks in Advance
Have you ensured the redirect uri passed to /token is the same as the one you passed to /authorize
I believe, it will help if you can test the OAuth auth code flow with your current client id, secret and scope using Postman tool in order to rule out bad configuration.
Please refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.

org.springframework.web.HttpRequestMethodNotSupportedException when trying to make POST call ( https://url/test)

## sendPost method to make the POST call. It is fetching the url and also printing the data properly in the below method. ##
Public static void sendPost(String url, String data) throws Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", "Mozilla/5.0");
StringEntity requestEntity = new StringEntity(data);
post.setEntity(requestEntity);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.[`enter link description here`][1]append(line);
}
System.out.println(result.toString());
}
}
#RequestMapping(value="/test", method = RequestMethod.POST)
public #ResponseBody String sendTestData(#RequestBody TestDTO TestData) {
try{
log.info("Data got to ingestion rest: "+TestData);
String jsonData = new Gson().toJson(TestData).toString();
System.out.println("jsonData=="+ jsonData);
boolean result = dataIngestionHandler.insertData(jsonData);
if(result){
return "SUCCESS";
}
}catch(Exception ex) {
log.error("Error while inserting data into the db!!");
return "FAIL" + ex.getMessage();
}
return "FAIL";
}
I am sending the data from the sendPost method to the controller method, but in response it is giving:
405 exception
Exact error
code:{"timestamp":1467696109585,"status":405,"error":"Method Not
Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request
method 'POST' not supported","path":"/test"}.
The entire setup is running fine and data is getting inserted into the db when I run it on localhost. But as soon as I push it to cloud, the following exception comes up

Push data into power bi using java azure ad library

I am knew to java, azure ad and power bi and I want to test pushing data into power bi using the azure ad java library (ADAL) here : http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java
I've created a netbeans project and used this code : http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java and tested it so that I know I have all rights to access my azure ad application.
In the Power BI documentation, we tell you to register your app and get the authentication token which will help you use the API to send GET/POST.. requests
I used a sample code I found on Github. However, following the examples in the power bi apiary docs I get a "403" or "404" http reponse status.
public class ApplicationAuthExample {
private final static String AUTHORIZATION_ENDPOINT = "https://login.microsoftonline.com/";
private final static String ARM_ENDPOINT = "https://management.azure.com/";
private static final boolean DEV_MODE = true;
public static void main(String[] args) throws Exception {
String username = null;
String credential = null;
String tenantId = null;
String clientId = null;
String subscriptionId = null;
if (DEV_MODE) {
username = "name.name#entity.com";
credential = "******";
clientId = "50xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
tenantId = "bbexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
subscriptionId = "16bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
} else {
if ((!args[0].equals("service-principal") && !args[0].equals("user"))
|| (args[0].equals("user") && args.length != 6)
|| (args[0].equals("service-principal") && args.length != 5)) {
System.out.println("Usage:");
System.out.println(" user <username> <password> <client id> <tenant id> <subscription id>");
System.out.println(" service-principal <password> <client id> <tenant id> <subscription id>");
System.exit(1);
}
int idx = 1;
if (args[0].equals("user")) {
username = args[idx++];
}
credential = args[idx++];
clientId = args[idx++];
tenantId = args[idx++];
subscriptionId = args[idx++];
}
// use adal to Authenticate
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
String url = AUTHORIZATION_ENDPOINT + tenantId + "/oauth2/authorize";
context = new AuthenticationContext(url,
false,
service);
Future<AuthenticationResult> future = null;
if (username == null) {
System.out.println("username = null");
ClientCredential cred = new ClientCredential(clientId, credential);
future = context.acquireToken(ARM_ENDPOINT, cred, null);
} else {
future = context.acquireToken(ARM_ENDPOINT, clientId,
username, credential, null);
}
result = future.get();
} catch (Exception ex) {
System.out.println("Exception occurred:");
ex.printStackTrace();
System.exit(1);
} finally {
service.shutdown();
}
// make a request to list available providers
String url = ARM_ENDPOINT
+ "subscriptions/" + subscriptionId
+ "/providers"
+ "?api-version=2014-04-01-preview";
// String url = "https://api.powerbi.com/v1.0/myorg/datasets";
String body = null;
try {
//final HttpClient httpClient = new DefaultHttpClient();
final HttpClient httpClient = HttpClientBuilder.create().build();
//HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
System.out.println("url : "+url);
httpGet.addHeader("Authorization", "Bearer " + result.getAccessToken());
// httpGet.setHeader("Authorization", "Bearer " + result.getAccessToken());
// System.out.println("token : "+result.getAccessToken());
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("status : "+statusCode);
if(statusCode == 403){
System.out.println(statusCode+": acces denied");
}
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(instream), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
instream.close();
body = sb.toString();
} catch (Exception ex) {
System.out.println(ex.toString());
System.exit(1);
}
System.out.println("body : "+body);
}
}
Thank you for your help.
As I known, the endpoints in your code are only for service on Azure, not for PowerBI. Please follow the PowerBI offical document to set the endpoints for authenticating, and see the document Push data into a Power BI Dashboard to know how to get started.
For authenticating to PowerBI service, please according to your needs to register a client app or a web app that needs different authentication.
There is a sample which I searched in GitHub, that includes the code for getting access token for PowerBI authentication using Java, please see https://github.com/satalyst/powerbi-rest-java/blob/master/src/main/java/com/satalyst/powerbi/impl/Office365Authenticator.java.
Hope it helps.
Any concern, please feel free to let me know.
After testing it in C# and going back to java, I finally managed to establish the connexion and get a valid token:
public class ApplicationAuth {
public static void main(String[] args) throws Exception {
String username = null;
String credential = null;
String clientId = null;
username = "xxxx.xxxxx#company.com";
credential = "************";
clientId = "50xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
// use adal to Authenticate
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
String url = "https://login.windows.net/common/oauth2/authorize";
context = new AuthenticationContext(url,
false,
service);
Future<AuthenticationResult> future = null;
if (username==null) {
System.out.println("username = null");
ClientCredential cred = new ClientCredential(clientId, credential);
future = context.acquireToken("https://analysis.windows.net/powerbi/api", cred, null);
} else {
future = context.acquireToken("https://analysis.windows.net/powerbi/api", clientId,
username, credential, null);
}
result = future.get();
} catch (Exception ex) {
System.out.println("Exception occurred:");
ex.printStackTrace();
System.exit(1);
} finally {
service.shutdown();
}
String body = null;
String token = result.getAccessToken();
try {
DatasetsHandler datasetH = new DatasetsHandler();
String data = "{\"name\": \"JavaDatasetTest\", \"tables\": " +
"[{\"name\": \"Product\", \"columns\": " +
"[{ \"name\": \"ProductID\", \"dataType\": \"Int64\"}, " +
"{ \"name\": \"Name\", \"dataType\": \"string\"}, " +
"{ \"name\": \"Category\", \"dataType\": \"string\"}," +
"{ \"name\": \"IsCompete\", \"dataType\": \"bool\"}," +
"{ \"name\": \"ManufacturedOn\", \"dataType\": \"DateTime\"}" +
"]}]}";
//datasetH.CreateDataset(data, token);
System.out.println("after creating dataset");
body = datasetH.GetDatasets(token);
String datasetID = datasetH.GetDatasetID(token);
System.out.println("dataset ID: "+datasetID);
String rows = "{\"rows\":" +
"[{\"ProductID\":1,\"Name\":\"Adjustable Race\",\"Category\":\"Components\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}," +
"{\"ProductID\":2,\"Name\":\"LL Crankarm\",\"Category\":\"Components\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}," +
"{\"ProductID\":3,\"Name\":\"HL Mountain Frame - Silver\",\"Category\":\"Bikes\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}]}";
String resu = datasetH.AddRows( datasetID, token, "Product", rows);
}catch (Exception ex) {
System.out.println(ex.toString());
System.exit(1);
}
// System.out.println("body : "+body); //{"value":[]}
}
}
Here are the methods I use:
public class DatasetsHandler {
public String powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
public String GetDatasets(String token) throws IOException{
HttpRequests httpRequest = new HttpRequests();
HttpResponse response = httpRequest.HttpHeaderParams(token, powerBIDatasetsApiUrl, "GET", "");
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(instream), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
instream.close();
String body = sb.toString();
return body;
}
public void CreateDataset(String data, String token) throws IOException{
HttpRequests httpRequest = new HttpRequests();
HttpResponse response = httpRequest.HttpHeaderParams(token, powerBIDatasetsApiUrl, "POST", data);
System.out.println("createDataset response: "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
System.out.println("entity: "+entity);
InputStream instream = entity.getContent();
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(instream), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
instream.close();
String body = sb.toString();
System.out.println("created dataset");
}
public String GetDatasetID(String token) throws IOException{
int id_count = 0;
DatasetsHandler DatasetH = new DatasetsHandler();
String result = DatasetH.GetDatasets(token);
JSONObject jObject = new JSONObject(result);
JSONArray geodata = jObject.getJSONArray("value");
for (int i = 0; i<geodata.length(); i++){
try{
JSONObject cdataset = geodata.getJSONObject(i);
id_count = id_count +1;
}catch (JSONException e) {
// If id doesn't exist, this exception is thrown
}
}
JSONObject cdataset = geodata.getJSONObject(id_count -1);
String Id = cdataset.getString("id");
System.out.println("get dataset name : "+cdataset.getString("name"));
System.out.println("get dataset id : "+cdataset.getString("id"));
return Id;
}
public String AddRows(String DatasetID, String token, String TableName, String rows) throws IOException{
String url = "https://api.powerbi.com/v1.0/myorg/datasets/"+DatasetID+"/tables/"+TableName+"/rows";
HttpRequests httpRequest = new HttpRequests();
HttpResponse response = httpRequest.HttpHeaderParams(token, url, "POST", rows);
System.out.println("Rows Added");
return response.getEntity().toString();
}
}
And the HttpHandelr:
public class HttpRequests {
public HttpRequestBase httpRequest;
public static Gson gson = new Gson();
public HttpResponse HttpHeaderParams (String token, String powerBIApiUrl, String method, String body) throws IOException {
final HttpClient httpClient = HttpClientBuilder.create().build();
//JSONObject jsonObj = new JSONObject(body);
StringEntity dataset = new StringEntity(body);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
if("GET".equals(method)){
httpRequest = new HttpGet(powerBIApiUrl);
}else if("POST".equals(method)){
System.out.println("===POST METHOD");
httpRequest = new HttpPost(powerBIApiUrl);
((HttpPost)httpRequest).setEntity(dataset);
System.out.println("get entity: "+((HttpPost)httpRequest).getEntity());
}
System.out.println("TOKEN: "+token);
httpRequest.setConfig(requestConfig);
httpRequest.addHeader("Authorization", "Bearer " + token);
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setHeader("ContentLength", "\""+body.length()+"\"");
HttpResponse response = httpClient.execute(httpRequest);
System.out.println("response: "+Arrays.toString(response.getAllHeaders()));
System.out.println("response: "+response.getStatusLine().getStatusCode());
return response;
}
}
I hope It helps :)

Android do PATCH/PUT to server

I'm having this issue and I need to put or patch data to the server. I know how to do a standard post, but how can I do this PATCH or PUT to the server?
The URL to the server is PATCH to www.example.com/api/documents and parameter is doc_id(integer).
This is what I currently have
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
httpPost.setHeader("accept-charset", "utf8");
try {
HttpResponse response = httpClient.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("Request exception:", "excpetion", e);
}
return responseString;
But this code I think is wrong as hell :)
This is the most common way---
Creating jsonObj and putting json values:
JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);
This is the callPutService that is called:
public String callPutService(String userName, String password,
String type, JSONObject jsonObject) {
String line = null, jsonString = "";
HttpResponse response = null;
InputStream inputStream = null;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.
setConnectionTimeout
(client.getParams(), 20000); // Timeout Limit
HttpPut put = new HttpPut(WEBSERVICE + type);
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
put.setHeader("Authorization",
"basic " + Base64.
encodeToString((userName + ":" + password).getBytes(),
Base64.URL_SAFE | Base64.NO_WRAP));
put.setEntity(se);
response = client.execute(put);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
//do whatever
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}

Android web view not sending post array to php?

the problem is that i don't receive any $_POST['registerationID'] from android webview
i have this code in android java ::
#Override
protected void onRegistered(Context context, String registrationId) {
String URL_STRING = "http://mysite.org/mysite/index.php/user/notification/";
Log.i(MyTAG, "onRegistered: registrationId=" + registrationId);
// notification
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("registrationId",registrationId));
try{
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setHeader("Content-Type","text/plain");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
HttpResponse response = httpclient.execute(httppost);
Log.i("LinkPOST:", httppost.toString());
Log.i("postData", response.getStatusLine().toString());
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null){
//System.out.println("Not Empty");
String responseBody = EntityUtils.toString(httpEntity);
System.out.println(responseBody);
} else {
System.out.println("Empty");
}
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and i handle the httprequest post in php (using codeigniter) as the following :
function notification() {
$registrationId = $_POST['registrationId'];
if($this->session->userdata('emailid')) {
//echo 'working from inside the if statement'.$this->session->userdata('emailid');
//$query = $this->db->query('INSERT INTO user (`deviceid`) VALUES ('.$_GET['registerationID'].') where `emailid`='.$this->session->userdata('emailid').';');
$data = array(
'deviceid' => $registrationId,
);
$this->db->where('emailid', $this->session->userdata('emailid'));
$this->db->update('user', $data);
if($this->db->affected_rows() == 1) {
// some code
}
else {
// some code
}
}
Try with the function bellow. It works for me.
Just Fill a HashMap for your post params
private static void post(String url, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
Try replacing
httppost.setHeader("Content-Type","text/plain")
by
httppost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8")
which is expected by your php code.
For more detail please see this SO question

Categories