2015-12-03 44 views
0

我跟着this POST数据到服务器并获得响应如何将数据发布到服务器并获取响应?意向?

在这里,我通过意图传递数据我用在主要活动

Intent i = new Intent(this, Mydata.class); 
      i.putExtra("data", data); 
      startActivity(i); 

用于接收意向下面的意图我用这个

Intent i = getIntent(); 
     String data = i.getExtras().getString("data"); 

这里的数据不通过URL ..

这是我的代码:

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.URL; 
import java.net.URLConnection; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.widget.TextView; 

public class Sdata extends Activity { 

    TextView content; 
    String utext; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     content = (TextView)findViewById(R.id.content); 

     try{ 

      GetData(); 
     } 
     catch(Exception ex) 
     { 
      content.setText(" url exeption! "); 
     } 

    } 

    public void GetData() 
    { 

     Intent i = getIntent(); 
     String data = i.getExtras().getString("data"); 

     String text = ""; 
     BufferedReader reader=null; 

     try 
     { 
      utext="http://google.com/api/?" + data; 
      URL url = new URL("utext"); 


      URLConnection conn = url.openConnection(); 
      conn.setDoOutput(true); 
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(data); 
      wr.flush(); 

      reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 

      while((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
      text = sb.toString(); 
     } 
     catch(Exception ex) 
     { 

     } 
     finally 
     { 
      try 
      { 

       reader.close(); 
      } 
      catch(Exception ex) {} 
     } 

     content.setText(text); 
     ((TextView) findViewById(R.id.text5)).setText(utext); 

    } 

} 

在此之后,我需要从服务器获取样反应

"Username Login Success" 
"Username Logout Success" 
or "Invalid User" 

更新:

在这里,我没有使用任何JSON数据或JSONstring和我的数据是

String data = "userid" + "=" + userid; 
      data += "&" + "phone" + "=" + phone; 
      data += "&" + "device" + "=" + device; 
      data += "&" + "clock_time" + "=" + "00:00:00"; 
      data += "&" + "clock_date" + "=" + clock_date; 

任何人都可以暗示我......

+0

为什么提到Php?我没有看到PHP代码。 – netrox

+0

在这里我的serveris PHP ...检查示例...链接我有 –

+0

你应该尝试使用jsoup它使这个东西更容易,并在android上运行良好,为什么不做这个职位,并获得第二个活动并发送如果用户登录错误,用户返回主要活动? –

回答

0

你可以参考下面的东西,你也应该和服务器端一起工作。

 HttpClient httpclient = new DefaultHttpClient(); 
     String mUrl = "https://url"; 
     HttpPost httppost = new HttpPost(mUrl); 
     httppost.addHeader("Content-Type", "application/json"); 
     JSONObject object = new JSONObject(); 
     object.put("data", "data"); 
     object.put("data2", "data2"); 
     StringEntity se = new StringEntity(object.toString(),"UTF-8"); 
     httppost.setEntity(se); 
     HttpResponse response = httpclient.execute(httppost); 
     if (response != null) { 
      result = EntityUtils.toString(response.getEntity()); 
     } 
+0

是否有任何方式与上面的URl一起工作我的意思是我的我的网址在这里“数据”我得到了很多字符串...... concaten –

+0

DefaultHttpClient在api-22中被弃用,并在api-23中被删除。 –

+0

Ho Ok有没有你的代码的任何完整的教程,, ..我是新来的机器人或其他可以你更新我的代码的答案... –

0

尝试使用jsoup,做这样的事情

Handler loginhandler; 
TextView yourTextView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 

    yourTextView = (TextView) findViewById(R.id.yourtextviewid); 

    //here you create a handler to which you will be sending messages from the thread 
    loginhandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      if (""+msg.obj == "Logged in"){ 
        //if the user logged in successfully then you take him to the next activity 
        Intent startIntent = new Intent(getApplicationContext(), YourNextActivity.class); 
        startActivity(startIntent); 
        finish(); 
      } 
      yourTextView.setText(""+msg.obj); 
     } 
    }; 

    //here you create an instance of the thread class you created further down and you start it 

    Thread loginThread = new Thread(new loginThread()); 
    loginThread.start(); 


} 

//your method that gets and posts data to internet that you will call from the thread 
public String getData(){ 


    Connection.Response loginForm = Jsoup.connect("Yourserver/login.php") 
      .method(Connection.Method.GET) 
      .execute(); 

    Connection.Response dataPage = Jsoup.connect("yourserver/login.php") 
      .data("_username", "Users login") 
      .data("_password", "users password") 
      .cookies(loginForm.cookies()) 
      .method(Connection.Method.POST) 
      .execute(); 

    Document ParsedDataPage = dataPage.parse(); 
    Element pageLoginStatus = ParsedDataPage.select("div.login-status").get(0); 
    String dataToReturn = Jsoup.parse(""+pageLoginStatus).text(); 
    return dataToReturn; 
} 

//here you create your thread in a class that implements Runnable and you put inside the run() method what you want it to do 
private class loginThread implements Runnable { 

    @Override 
    public void run() { 
     try { 
      String myData = getData(); 

      //here you create a message and send it to your handler that you created above 
      Message message = Message.obtain(); 
      message.obj = myData; 
      loginhandler.sendMessage(message); 
     } 
     catch (Exception e){ 
      //Do something with the exception here 
     } 
    } 
} 

好吧,我基本上写你的整个代码,现在你只需要做一些修改。数据(),您发送到服务器取决于你想发送的数据,你应该看看网站的html代码,然后你所要做的就是把这些代码放到你的类中去实现Activity。您还必须下载Jsoup库并将其放入外部库文件夹中。

你应该看一篇关于线程如何工作的教程,因为如果你打算在Android上做互联网的东西,你将会使用它们很多。

+0

中不推荐使用sir我是android的新手可以更新你的代码我的代码..你的代码很好,但不能用我的代码' –

+0

@ Don'tBenegative我编辑了代码,但你应该阅读一些关于线程的文档,并在Jsoup中使用它之前工作一点,我在做什么是在eclipse中写我的java代码到确保一切正常,然后我将这些方法复制到我的Android应用 –

0

您可以尝试使用单独的方法将日期发布到服务器,这里是示例代码...您可以参考它。

public String postData(String sURL,String sData) 
    { 
     try 
     { 
      String data = URLEncoder.encode("jsonString", "UTF-8")+ "=" + URLEncoder.encode(sData, "UTF-8"); 
      URL url = new URL(sURL); 
      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; 

      while((line = reader.readLine()) != null) 
       { 
         sb.append(line + "\n"); 
       } 
      System.out.println("POST Respon "+sb.toString()); 
      return sb.toString(); 

     }catch(Exception e) 
     { 

     } 
     return ""; 
    } 
+0

这里什么是surl ...或者哪里是URL这里我没有使用任何JSON字符串 –

+0

utext =“http://google.com/api/?” +数据; –

+0

@ hemanth1087你可以在我的完整代码中更新你的答案...我是新来的android我试过的代码但它不工作...在这里,我通过意图获取数据我应该在哪里使用它... –

相关问题