我是编程方面的 android 菜鸟,但在一些程序的帮助下,我可以学习基础知识。我想对 arduino ethernetshield 做一个基本的 http get 请求。
为此,我找到了一些代码,但我无法让它工作。我一直坚持使用我从几页尝试过的代码的 getResponse 部分。
我发现以下页面给了我可读的代码: 如何在 android 中使用 url 处理图像?
现在我创建了以下内容:按下一个按钮并访问一个 url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
我在哪里可以找到有关如何正确编写代码的信息?或者你碰巧有某种暗示的答案,所以我可以从中学习?