Rectangle 27 2

This is an illustration for making a POST request using Volley. StringRequest is used to get response in the form of String. Assuming your rest API returns a JSON. The JSON response from your API is received as String here, which you can covert again to JSON and process it further. Added comments in code.

StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        // Process your json here as required
                    } catch (JSONException e) {
                        // Handle json exception as needed
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String json = null;
                    NetworkResponse response = error.networkResponse;
                    if(response != null && response.data != null){
                        switch(response.statusCode) {
                            default:
                                String value = null;
                                try {
                                    // It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
                                    value = new String(response.data, "UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                json = trimMessage(value, "message");
                                // Use it for displaying error message to user 
                                break;
                        }
                    }
                    loginError(json);
                    progressDialog.dismiss();
                    error.printStackTrace();
                }  
                public String trimMessage(String json, String key){
                    String trimmedString = null;
                    try{
                        JSONObject obj = new JSONObject(json);
                        trimmedString = obj.getString(key);
                    } catch(JSONException e){
                        e.printStackTrace();
                        return null;
                    }
                    return trimmedString;
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("abc", "pass abc");
            params.put("xyz", "pass xyz");
            // Pass more params as needed in your rest API
    // Example you may want to pass user input from EditText as a parameter
    // editText.getText().toString().trim()
            return params;
        }  
        @Override
        public String getBodyContentType() {
            // This is where you specify the content type
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    };

    // This adds the request to the request queue
    MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);
public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mCtx;  
    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }
}

How do you use the Android Volley API? - Stack Overflow

android android-volley
Rectangle 27 3

You can send a get/post request to log on the server. The PHP page can return JSON or XML. Then your Java (Android) code will have to parse that response.

You can have the PHP page log first, and then start a session. Maybe generate a token key and store this in the database, and then return this to the android app. Android app will get this token (after parsing), and probably save it in a preferences file. This approach is basically a custom session. You will have to figure out things like expiration of token, etc.

There might be a way to store PHP sessions, but not sure how an app behaves differently from a browser. I think sessions can be little bit more complicated with apps.

"save it in a preferences file" - that would be extremely slow.

You could store it in the database, but it would make things too complicated just for one string.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Connecting Android App to PHP Server - Stack Overflow

php android networking web
Rectangle 27 2

Logout and Login

public class MainActivity extends FragmentActivity {
    String TAG="MainActivity";
    private static final String PERMISSION = "publish_actions";

    //private static final String PERMISSION = "email";

    private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

    private Button postStatusUpdateButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;

    Button LogoutButton,Pro;

/*  private static final List<String> PERMISSION = Arrays.asList(
            "email","publish_actions");*/


    private enum PendingAction
    {
        NONE, POST_STATUS_UPDATE
    }

    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) 
        {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall,
                Exception error, Bundle data) {
            Log.d(TAG, String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall,
                Bundle data) {
            Log.d(TAG, "Success!");
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_main);



        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
        {
                    @Override
                    public void onUserInfoFetched(GraphUser user) 
                    {
                        MainActivity.this.user = user;
                        updateUI();
                        // It's possible that we were waiting for this.user to
                        // be populated in order to post a status update.
                        handlePendingAction();


                    }
                });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
            }
        });

          LogoutButton=(Button)findViewById(R.id.LogoutButton);
          LogoutButton.setOnClickListener(new View.OnClickListener() 
          {

            @Override
            public void onClick(View v)
            {

                //callFacebookLogout(session);
                Logout();

            }
        });

    }

    //override lifecycle methods so that UiLifecycleHelper know about state of the activity
    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state,Exception exception) 
    {
        if (state.isOpened()) {
            Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

            getUserData(session,state);



        } else if (state.isClosed()) {
            Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
        }
        if (pendingAction != PendingAction.NONE
                && (exception instanceof FacebookOperationCanceledException 
                || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() 
    {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons
                || canPresentShareDialog);

        if (enableButtons && user != null) 
        {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));



        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }


    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result,
            FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post,
                    message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null).show();
    }

    // create sample post to update on facebook
    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                .setLink("http://androidsrc.net/");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update,
                    user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message, place, tags,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message,
                                    response.getGraphObject(),
                                    response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    //check if app has permission to publish on facebook
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when
                // we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    public void Logout()
    {
        if (Session.getActiveSession() != null) 
        {
            Session.getActiveSession().closeAndClearTokenInformation();
            Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
        }

        Session.setActiveSession(null);
    }




    private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                           // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }
    }
public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }

Facebook SDK 3.0 Logout Not Working in android Application from any ot...

android facebook facebook-login facebook-android-sdk
Rectangle 27 71

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

Can you please suggest, how can I restrict the encrypt passed URL, so that no one can see as it is POST.

@MKS - You can't really, not without proxying it through your own domain...GET requests are inherently "open", much more so than a POST

Thanks @NICK, can you please suggest is it safe going with "GET" instead of "POST", what can be the drawbacks of using "GET"..please suggest

@T.J. - well, with SSL is can be drastically more secure though, if your payload is in the POST and not the URL, that was more what I was aiming at.

The notion that GET requests over SSL are less secure than POSTs when in transit is incorrect. URL info such as path, query string, etc are all encrypted as part of the HTTP request. Your query string cannot be "sniffed" at the packet level. There are other concerns, however, as outlined in the answer to this SO question

jquery - How to use type: "POST" in jsonp ajax call - Stack Overflow

jquery jsonp http-post
Rectangle 27 0

The attached is a Maven project;
The server side code is implemented as a Spring MVC controller;
The client side code is implemented in the simple "index.jsp" file;
The project uses Java 8 and Tomcat 7. If you want to try this example by yourself, I would recommend JDK 8 and Eclipse Luna Java EE IDE for web developers or above.
I will assume that you have some general background on Maven, Spring MVC, and jQuery. If you are not familiar with these, you can always check out the internet to get the ideas on them.

The server side code
The attached is a Maven project, the POM file is the following:

Hide   Shrink    Copy Code
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.song.example</groupId>
  <artifactId>jquery-simple-upload</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

    <properties>
        <spring.version>4.1.7.RELEASE</spring.version>
        <jackson.version>2.6.1</jackson.version>
        <tomcat.version>7.0.55</tomcat.version>
    </properties>

    <dependencies>
        <!-- Minimal dependencies for Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Multi-part file support -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- Jackson dependencies -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-databind</artifactId>
              <version>${jackson.version}</version>
        </dependency>

        <!-- Sevlet jars for compilation, provided by Tomcat -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>${tomcat.version}</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>     
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>webcontent</warSourceDirectory>
                    <failOnMissingWebXml>true</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                    </configuration>
                </plugin>
        </plugins>
    </build>
</project>
The "web.xml" and the "mvc-dispatcher-servlet.xml" file are the following:

Hide   Shrink    Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">

    <display-name>D3 Example</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>nocachefilter</filter-name>
        <filter-class>com.song.example.filter.NocacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>nocachefilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
          <servlet-class>
              org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
          <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>BaseUrl</param-name>
          <param-value>
            http://localhost:8080/jquery-simple-upload/
          </param-value>
    </context-param>

</web-app>
Hide   Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

     <context:component-scan base-package="com.song.example.controller" />
     <mvc:annotation-driven />

     <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>
The MVC controller that takes the uploaded file is implemented in the "FileController" file:

Hide   Shrink    Copy Code
package com.song.example.controller;

import java.io.InputStream;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class FileController {

    @RequestMapping(value = "/echofile", method = RequestMethod.POST, produces = {"application/json"})
    public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
            HttpServletResponse response) throws Exception {

        MultipartFile multipartFile = request.getFile("file");
        Long size = multipartFile.getSize();
        String contentType = multipartFile.getContentType();
        InputStream stream = multipartFile.getInputStream();
        byte[] bytes = IOUtils.toByteArray(stream);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("fileoriginalsize", size);
        map.put("contenttype", contentType);
        map.put("base64", new String(Base64Utils.encode(bytes)));

        return map;
    }
}
The "echoFile()" method takes the uploaded file though the "MultipartHttpServletRequest" object;
It converts the file content into Base64 format and returns the Base64 content in the JSON response;
The goal of this example is to use jQuery Ajax to upload a file to the server and receive the responded JSON object. Now let us take a look at the client side code.

The client side code
The client side code is implemented in the "index.jsp" file. The HTML part of the file is the following:

Hide   Copy Code
<body style="font-family: calibri; font-size: 8pt">
<div>
<form id="fileForm">
    <input type="file" name="file" />
    <button id="btnUpload" type="button">Upload file</button>
    <button id="btnClear" type="button">Clear</button>
</form>
<div id="imgContainer"></div>
</div>
</body>
The Javascript part of the file is the following:

Hide   Shrink    Copy Code
<script type="text/javascript">

var isJpg = function(name) {
    return name.match(/jpg$/i)
};

var isPng = function(name) {
    return name.match(/png$/i)
};

$(document).ready(function() {
    var file = $('[name="file"]');
    var imgContainer = $('#imgContainer');

    $('#btnUpload').on('click', function() {
        var filename = $.trim(file.val());

        if (!(isJpg(filename) || isPng(filename))) {
            alert('Please browse a JPG/PNG file to upload ...');
            return;
        }

        $.ajax({
            url: '<%=baseUrl%>api/echofile',
            type: "POST",
            data: new FormData(document.getElementById("fileForm")),
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false
          }).done(function(data) {
              imgContainer.html('');
              var img = '<img src="data:' + data.contenttype + ';base64,'
                  + data.base64 + '"/>';

              imgContainer.append(img);
          }).fail(function(jqXHR, textStatus) {
              //alert(jqXHR.responseText);
              alert('File upload failed ...');
          });

    });

    $('#btnClear').on('click', function() {
        imgContainer.html('');
        file.val('');
    });
});

</script>
The jQuery reference is to the jQuery CDN "<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>". If you want to run this example on your own computer, you need to make sure that you have the internet access, so your browser can download jQuery from the CDN.

The HTML part declared a file input in an HTML form;
In the click event of the "btnUpload" button, an Ajax call is issued to upload the file. The data to be uploaded is a "FormData" object;
Upon a success Ajax call, a JSON response is received. The JSON object should have the Base64 content responded from the server.
In order to show the responded data, I insisted that only JPG/PNG images can be uploaded. The responded Base64 image will be displayed on the web page.

asp.net - Send value and file from view to controller by ajax method -...

asp.net ajax file controller asp.net-mvc-5
Rectangle 27 -1

/*********See this**********/
-(void)webServiceCall{

NSString *dataToSend = [NSString stringWithFormat:@"Username=%@&Password=%@,<userIdEnter Here>,<Password enter here>]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
NSString *Length = [NSString stringWithFormat:@"%d",[postData length]]; 

[request setURL:[NSURL URLWithString:@WEBURL]]; 
[request setHTTPMethod:@"POST"]; 

[request setValue:Length forHTTPHeaderField:@"Content-Length"]; 

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 


 }
// check connection if you want

/*****get response in delegates*******/



 - (void)connection:(NSURLConnection *)connection didReceiveResponse:
  (NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it

    _responseData = [[NSMutableData alloc] init];

      }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
    {
         /**************/
  NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                         options:kNilOptions
                                                           error:&error];

   // NSArray* latestLoans = [json objectForKey:@"loans"];

    NSLog(@"json: %@", json);

    [_responseData appendData:data];



    }
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
    {
 NSLog(@"Error --> %@",error.localizedDescription);
        /***************/
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
 NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];

 NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
// use Result
self.responseData = nil;

    }

what to write in Response delegates? @ajjjjjjjj

Seriously I'm not understanding it can u elaborate the code please? Where to write this code how we get response and where to write response delegate? @ajjjjjjjj

First you have to paste the code in class where you want to call web service. now, call method webServiceCall on login Button click, where you have to change user_id and password entered by user. After call happened, 'NSUrlConnection' delegate will called(read delegate documentation). After getting response in connectionDidFinishLoading. You have to parse data in this way ` id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; `. After that you can use 'result'

ios - How to POST data using JSON service in Objective c - Stack Overf...

ios objective-c xcode8