Scala- JSON HTTP Post请求抛出错误

时间:2014-05-19 09:23:34

标签: java json apache scala

我有一些scala代码,用于处理http post请求。 下面提到的是示例代码,

import java.io._
import org.apache.commons._
import org.apache.http._
import org.apache.http.client._
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import java.util.ArrayList
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import com.google.gson.Gson

case class Person(firstName: String, lastName: String, age: Int)

object HttpJsonPostTest extends App {

  // create our object as a json string
  val spock = new Person("I love java")
  val spockAsJson = new Gson().toJson(spock)

  // add name value pairs to a post object
  val post = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson")
  val nameValuePairs = new ArrayList[NameValuePair]()

  nameValuePairs.add(new BasicNameValuePair("JSON", spockAsJson))
  post.setEntity(new UrlEncodedFormEntity(nameValuePairs))

  // send the post request
  val client = new DefaultHttpClient
  val response = client.execute(post)

  println("--- HEADERS ---")
  response.getAllHeaders.foreach(arg => println(arg))
}

ERROR:While running this application, it is showing "Project sample contain build errors, Continue launch? "

控制台中的

Error: Could not find or load main class sample.HttpJsonPostTest

请有人帮助我,我们将不胜感激。

谢谢, Reddi Babu

1 个答案:

答案 0 :(得分:0)

你的代码没有编译,你有这个案例类:

case class Person(firstName: String, lastName: String, age: Int)

在这个过程中,您要在不指定所有参数的情况下实例化新的Person

val spock = new Person("I love java")

您需要添加所有参数:

val spock = Person("I love java", "some lastname", 18)

或者在案例类中指定默认值:

case class Person(firstName: String, lastName: String = "some last name", age: Int = 18)

修复此错误后,我收到了回复:

--- HEADERS ---
Date: Mon, 19 May 2014 09:47:52 GMT
Content-Type: text/html
Server: Google Frontend
Content-Length: 0
Alternate-Protocol: 80:quic,80:quic

另请注意,案例类的new不是必需的。